LeetcodeLeetCode solutions算法提高之LeetCode刷题

LeetCode547. Friend Circles

2018-04-05  本文已影响3人  Stan95
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect friends. Given a N*N matrix M representing the friend relationship between students in the class. If M[i][j] = 1, then the ith and jth students are direct friends with each other, otherwise not. And you have to output the total number of friend circles among all the students.
Example 1:

Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2

Explanation:The 0th and 1st students are direct friends, so they are in a friend circle. The 2nd student himself is in a friend circle. So return 2.

Solution: I use DFS to traverse all the elements in the array. We use extra O(N) space to store the elements have been visited or not. If it has been visited, we jump that.
class Solution{
public int findCircleNum(int[][] M) {
        int  count = 0;//store the current circle value.
        int[] visited = new int[M.length];//store the visited conditions.
        for(int i = 0; i < M.length; i++){
            if(visited[i] == 0){//if not visited, we use dfs to explore.
                dfs(M,visited,i);
                count++;//each new start dfs, we increase the count as it has a new circle.
            }
        }
        return count;
    }
    public void dfs(int[][] M, int[] visited, int i){
        for(int j = 0; j < M.length; j++){
            if(M[i][j] == 1 && visited[j] == 0){//we actually evaluate the j element here
                visited[j] = 1;//set it as visited.
                dfs(M,visited,j);//explore it
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读