LeetCode-547. Number of Provinces

description

There are n cities, some of which are connected to each other, and some are not connected. If city a and city b are directly connected, and city b is directly connected to city c, then city a and city c are indirectly connected.

A province is a group of directly or indirectly connected cities. The group does not contain other unconnected cities.

Give you an nxn matrix isConnected, where isConnected[i][j] = 1 means that the ith city and the jth city are directly connected, and isConnected[i][j] = 0 means that the two are not directly connected.

Returns the number of provinces in the matrix.

 

Example 1:


Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2
Example 2:


Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
 

prompt:

1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j] 为 1 或 0
isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]

Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-provinces/

Solve

Investigate graph theory, that is, connected components in unweighted graphs, you can get by traversing the graph once with depth-first search

   class Solution {
    private:
        vector<bool> visited; // 标记顶点是否被访问过

        // 从v开始深度遍历图graph
        void dfs(const vector<vector<int>> &graph, const int n, int v) {
            visited[v] = true;
            // 遍历v的所有可达邻接点
            for (int i = 0; i < n; ++i) {
                if (!visited[i] && graph[v][i] == 1) {
                    dfs(graph, n, i);
                }
            }
        }

    public:
        // 利用图的深度遍历求解连通分量
        int findCircleNum(const vector<vector<int>> &isConnected) {
            int count = 0; // 记录连通分量
            const int N = isConnected.size();
            visited.assign(N, false);
            for (int i = 0; i < N; ++i) {
                if (!visited[i]) {
                    ++count;
                    dfs(isConnected, N, i);
                }
            }
            return count;
        }
    };

 

Guess you like

Origin blog.csdn.net/u010323563/article/details/112335228