Leetcode 547. Number of provinces (number of connected blocks, DFS)

1. Title description

There are n cities, some of which are connected to each other, and some of them 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 i-th city and the j-th city are directly connected, and isConnected[i][j] = 0 means that the two are not directly connected.

Returns matrix province number.

Example:

Insert picture description here

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

Insert picture description here

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

2. Solution

This is also a problem of calculating the number of connected blocks.

class Solution {
    
    
public:

    int findCircleNum(vector<vector<int>>& isConnected){
    
    
        int m = isConnected.size();
        int n = isConnected[0].size();
        int num = 0;
        for(int i = 0; i < m; i++){
    
    
            if(isConnected[i][i] == 1){
    
    
                DFS(i,isConnected);
                num+=1;
            }
        }
        return num;
    }
    void DFS(int x, vector<vector<int>>& isConnected){
    
    
        int n = isConnected[0].size();
        for(int i = 0;i < n;i++){
    
     //遍历一行
            if(isConnected[x][i] == 1){
    
     //找到一个联通的
                isConnected[x][i] = 0; //go!
                isConnected[i][x] = 0; //go!
                DFS(i,isConnected); //继续
            }
        }
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_41332009/article/details/114992083