Friend Circles

来源:互联网 发布:windows我的电脑图标 编辑:程序博客网 时间:2024/05/19 14:51

原题地址:点我传送

本质上是对一个领接矩阵做一个图的广度优先遍历,对每一个点,如果之前已经被遍历过,那么就已经存在于一个朋友圈中,无需再遍历。如果没有,则广度优先遍历并记录。最后的count便是答案。

C++:

class Solution {public:    int findCircleNum(vector<vector<int>>& M) {        int count = 0;        bool *visited = new bool [M.size()];        for(int i=0;i<M.size();i++)        {            visited[i] = false;        }        list<int> L;        for(int i=0;i<M.size();i++)        {            bool avail = false;            if(!visited[i])            {                L.push_back(i);                visited[i]=true;                avail = true;            }            while(L.size())            {                int temp = L.front();                L.pop_front();                for(int j=0;j<M[temp].size();j++)                {                    if(M[temp][j]&&!visited[j])                    {                        L.push_back(j);                        visited[j] = true;                    }                }            }            if(avail)            count++;        }        return count;    }};


Java:

使用了Queue容器的offer,poll,peak。

public class Solution {    public int findCircleNum(int[][] M) {        int count = 0;        boolean visited[] = new boolean [M.length];        Queue<Integer> L = new LinkedList<Integer>();        for(int i=0;i<M.length;i++)        {            boolean avail = false;            if(!visited[i])            {                L.offer(i);                visited[i]=true;                avail = true;            }            while(L.size()!=0)            {                int temp = L.poll();                for(int j=0;j<M[temp].length;j++)                {                    if((M[temp][j]!=0)&&(!visited[j]))                    {                        L.offer(j);                        visited[j] = true;                    }                }            }            if(avail)            count++;        }        return count;    }}



0 0
原创粉丝点击