HackerRank: Friend Circles (DFS in Java)
Welcome to Code Review. Your code is good and easy to read, you can iterate over only half of the matrix (in my case the elements of the matrix a[i,j] with i &lt; j) because from the test matrices always results a[i, j] = a[j, i] so friendship in symmetric .
I'm using a TreeMap&lt;Integer, Set&lt;Integer&gt;&gt; to store initial situation to guarantee natural order of the keys so it will always the lower index the index where friends will be added : everybody is friend of himself (reflexive property) so map[i]={ i }.

int n = friends.length;
Map&lt;Integer, Set&lt;Integer&gt;&gt; map = new TreeMap&lt;&gt;();
for (int i = 0; i &lt; n; ++i) {
    Set&lt;Integer&gt; set = new TreeSet&lt;&gt;();
    set.add(i);
    map.put(i, set);
}


Now I check all elements a[i, j] with i &lt; j and see if i appears as key in the map: if yes I add j to map[j], otherwise it means that i appears in another set and I will add j to this set. At the end in any case I will remove the key j:

for (int i = 0; i &lt; n; ++i) {
    for (int j = 0; j &lt; n; ++j) {
        if (i &lt; j &amp;&amp; friends[i][j] == 'Y') {
            if (map.containsKey(i)) {
                map.get(i).add(j);      
            } else {
                for (Integer key : map.keySet()) {
                    Set&lt;Integer&gt; set = map.get(key);
                    if (set.contains(i)) {
                        set.add(j);
                    }
                }
            }
            map.remove(j);
        }
    }
}


The number of circles will coincide with the number of keys present in the map at the end:

public static int CountFriendsCircles(char[][] friends) {
    int n = friends.length;
    Map&lt;Integer, Set&lt;Integer&gt;&gt; map = new TreeMap&lt;&gt;();
    for (int i = 0; i &lt; n; ++i) {
        Set&lt;Integer&gt; set = new TreeSet&lt;&gt;();
        set.add(i);
        map.put(i, set);
    }

    for (int i = 0; i &lt; n; ++i) {
        for (int j = 0; j &lt; n; ++j) {
            if (i &lt; j &amp;&amp; friends[i][j] == 'Y') {
                if (map.containsKey(i)) {
                    map.get(i).add(j);      
                } else {
                    for (Integer key : map.keySet()) {
                        Set&lt;Integer&gt; set = map.get(key);
                        if (set.contains(i)) {
                            set.add(j);
                        }
                    }
                }
                map.remove(j);
            }
        }
    }

    return map.size();
}