I got this problem on a HackerRank challenge and this was the best I could think of. Basically only DFS is used to find connected components (in this case groups of friends). It was hard for me to figure out how to track unvisited nodes. Please let me know how I can improve this code. It seems to work, but the test cases given were fairly simple.

**Problem:**

There are N students in a class. Some of them are friends, others are not. Their friendship is transitive in nature; H. If A is a friend of B and B is a friend of C, then A is also a friend of C. A circle of friends is a group of students who are friends, directly or indirectly.

You have to perform a function `int friendCircles(char()() friends)`

This returns the number of circles of friends in the class. His argument, friends, is a `NxN`

Matrix consisting of the characters "Y" or "N". If `friends(i)(j) == "Y"`

then ith and jth students are friends with each other, otherwise not. You must return the total number of circles of friends in the class.

```
Sample Input 0:
4
YYNN
YYYN
NYYN
NNNY
Sample Output 0:
2
Explanation 0:
There are two pairs of friends (0, 1) and (1, 2). So (0, 2) is also a pair of friends by transitivity.
So first friend circle contains (0, 1, 2) and second friend circle contains only student 3
Sample Input 1:
5
YNNNN
NYNNN
NNYNN
NNNYN
NNNNY
Sample output 1:
5
```

Restrictions (sorry, formatting could not be performed, so I had to set the restrictions here):

- 1 <= N <= 300.
- Each element of matrix friends is "Y" or "N".
- The number of rows and columns is the same for friends.
- Friends (i) (j) = "Y", where 0 <= i <N.
- Friends (i) (j) = Friends (j) (i), where 0 <= i <j <N.

**Solution:**

```
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.Set;
public class Solution {
public static int friendsCircle(char()() friends) {
// The only alternative I could think of, instead of
// tracking unvisited nodes, was to put visited nodes
// in a set and then do setOfAllNodes.removeAll(visited)
// to see which nodes are still unvisited
Set
``` unvisited = new HashSet<>();
boolean() visited = new boolean(friends.length);
Deque stack = new ArrayDeque<>();
int connectedComponents = 0;
for (int i = 0; i < friends.length; i++) {
unvisited.add(i);
}
// dfs on friends matrix
while (!unvisited.isEmpty()) {
stack.push(unvisited.iterator().next());
connectedComponents++;
while (!stack.isEmpty()) {
int currVertex = stack.pop();
if (visited(currVertex) == false) {
visited(currVertex) = true;
unvisited.remove(currVertex);
for (int i = 0; i < friends(currVertex).length; i++) {
if (friends(currVertex)(i) == 'Y' && visited(i) == false) {
stack.push(i);
}
}
}
}
}
return connectedComponents;
}
public static void main(String() args) {
char()() friends = {
{'Y','Y','N','N'},
{'Y','Y','Y','N'},
{'N','Y','Y','N'},
{'N','N','N','Y'}
};
System.out.println(friendsCircle(friends));
}
}