[DFS]LeetCode547. Friend Circles

[DFS]LeetCode547. Friend Circles_第1张图片

深度优先搜索,遍历完一棵树之后,选择下一个没有mark的点继续搜索

class Solution {
public:
    void countNum(vector>& M, int ith, bool marked[]) {
        marked[ith] = true;
        for(int i = 0; i < M.size(); i++) {
            if(M[ith][i] == 1 && marked[i] == false) {
                countNum(M, i, marked);
            }
        }
    }
    int findCircleNum(vector>& M) {
        bool* markedNum = new bool[M.size()];
        int circleNum = 0;
        for(int i = 0; i < M.size(); i++)
            markedNum[i] = false;
        for(int i = 0; i < M.size(); i++) {
            if(!markedNum[i]) {
                countNum(M, i, markedNum);
                circleNum++;
            }
        }
        return circleNum;
    }
};

你可能感兴趣的:([DFS]LeetCode547. Friend Circles)