xinyu04

导航

LeetCode 547 Number of Provinces 连通块个数

There are \(n\) cities. Some of them are connected, while some are not. If city \(a\) is connected directly with city \(b\), and city \(b\) is connected directly with city \(c\), then city \(a\) is connected indirectly with city \(c\).

A province is a group of directly or indirectly connected cities and no other cities outside of the group.

You are given an n x n matrix isConnected where isConnected[i][j] = 1 if the ith city and the jth city are directly connected, and isConnected[i][j] = 0 otherwise.

Return the total number of provinces.

Solution

\(vector\) 存边即可,然后对每个没有被访问的点进行 \(dfs\)

点击查看代码
class Solution {
private:
    int ans=0;
    vector<int> eg[210];
    int vis[203];
    
    void dfs(int x){
        if(vis[x])return;
        vis[x]=1;
        int sz = eg[x].size();
        for(int i=0;i<sz;i++){
            int to = eg[x][i];
            if(vis[to])continue;
            dfs(to);
        }
    }
    
public:
    int findCircleNum(vector<vector<int>>& isConnected) {
        int n = isConnected.size();
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(i==j) continue;
                if(isConnected[i][j])eg[i].push_back(j);
            }
        }
        for(int i=0;i<n;i++){
            if(!vis[i]){ans++;dfs(i);}
        }
        return ans;
    }
};

posted on 2022-08-02 18:01  Blackzxy  阅读(27)  评论(0编辑  收藏  举报