1. 程式人生 > 其它 >547. Number of Provinces(Leetcode每日一題-2021.01.07)

547. Number of Provinces(Leetcode每日一題-2021.01.07)

技術標籤:leetcode每日一題202101leetcode並查集

Problem

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.

Constraints:

  • 1 <= n <= 200
  • n == isConnected.length
  • n == isConnected[i].length
  • isConnected[i][j] is 1 or 0.
  • isConnected[i][i] == 1
  • isConnected[i][j] == isConnected[j][i]

Example1

在這裡插入圖片描述

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

Example2

在這裡插入圖片描述

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

Solution

class Solution {
public:
    vector<int> p;

    int find(int x) {
        if (p[x] != x) p[x] =
find(p[x]); return p[x]; } int findCircleNum(vector<vector<int>>& M) { int n = M.size(); for (int i = 0; i < n; i ++ ) p.push_back(i); int cnt = n; for (int i = 0; i < n; i ++ ) for (int j = 0; j < n; j ++ ) if (M[i][j] && find(i) != find(j)) { p[find(i)] = find(j); cnt -- ; } return cnt; } };