There are N students in the class. Some of them are friends, some are not. Their friendship is transitive. If it is known that A is a friend of B and B is a friend of C, then we can assume that A is also a friend of C. The so-called circle of friends refers to the collection of all friends.
Given an N*N matrix M representing the friend relationships among students in a class. If M[i][j] = 1, it means that the ith and j students are known to be friends, otherwise it is unknown. You must output the total number of known Moments among all students.
Example 1:
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Description: It is known that student 0 and student 1 are friends with each other, and they are in a friend lock up.
The second student himself is in a circle of friends. So return 2.
Example 2:
Input:
[[1,1,0],
[1,1,1],
[0,1,1]]
Output: 1
Description: It is known that student 0 and student 1 are friends, and student 1 and student 2 are friends with each other, so student 0 and student 2 are also friends, so the three of them are in a circle of friends, return 1.
Note:
1.N is in the range [1,200].
2. For all students, there is M[i][i] = 1.
3. If there is M[i][j] = 1, then there is M[j][i] = 1.
See: https://leetcode.com/problems/friend-circles/description/
C++:
class Solution { public: int findCircleNum(vector<vector<int>>& M) { int n = M.size(), res = 0; vector<bool> visited(n, false); for (int i = 0; i < n; ++i) { if (visited[i]) { continue; } helper(M, i, visited); ++res; } return res; } void helper(vector<vector<int>>& M, int k, vector<bool>& visited) { visited[k] = true; for (int i = 0; i < M.size(); ++i) { if (!M[k][i] || visited[i]) { continue; } helper(M, i, visited); } } };
Reference: http://www.cnblogs.com/grandyang/p/6686983.html