leetcode547. 省份数量(中等,求连通分量个数)

leetcode547. 省份数量(中等,求连通分量个数)_第1张图片
leetcode547. 省份数量(中等,求连通分量个数)_第2张图片
leetcode547. 省份数量(中等,求连通分量个数)_第3张图片
类似:leetcode200.岛屿数量(中等)

思路一:dfs

class Solution {
public:
    int flag[205] = {0};
    void dfs(vector<vector<int>>& isConnected, int m) {
        int n = isConnected.size();
        flag[m] = 1;
        for (int i = 0; i < n; ++i) {
            if (isConnected[m][i] && !flag[i]) {
                dfs(isConnected, i);
            }
        }
    }
    int findCircleNum(vector<vector<int>>& isConnected) {
        
        int n = isConnected.size(), ans = 0;
        for (int i = 0; i < n; ++i) {
            if (!flag[i]) {
                ans++;
                dfs(isConnected, i);
            }
        }
        return ans;
    }
};

思路二:bfs

void bfs(vector<vector<int>>& isConnected, int m) {

        int n = isConnected.size();
        queue<int> q;
        q.push(m);
        flag[m] = 1;
        while (!q.empty()) {
            int frt = q.front();
            q.pop();
            for (int i = 0; i < n; ++i) {
                if (isConnected[frt][i] && !flag[i]) {
                    q.push(i);
                    flag[i] = 1;
                }
            }
        }
    }

思路三:并查集
最后通过father[i] == i判断连通分量的个数

你可能感兴趣的:(#,图,深度优先,图论,leetcode)