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.
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
Constraints:
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j]
is1
or0
.isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]
题目中多次出现关键字connected,并且要求省份的个数(即集合个数),是一道典型的关于连通性合并的问题,毫无疑问可以用并查集(Union Find)来解答。
代码与求岛屿个数Leetcode200. Number of Islands大同小异,只是合并的条件略有不同,直接套用Union Find代码模板稍加修改即可。一道难度为Medium的题瞬间变成easy。
class UnionFind:
def __init__(self, n):
self.parent = list(range(0, n))
self.size = [1] * n
self.cnt = n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def merge(self, x, y):
px,py = self.find(x), self.find(y)
if px == py :
return
if self.size[px] > self.size[py]:
self.parent[py] = px
self.size[px] += self.size[py]
else:
self.parent[px] = py
self.size[py] += self.size[px]
self.cnt -= 1
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
n = len(isConnected)
uf = UnionFind(n)
for i in range(n):
for j in range(i + 1, n):
if isConnected[i][j] == 1:
uf.merge(i, j)
return uf.cnt