547. Number of Provinces
Medium
5181239Add to ListShare
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]
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
"""
assert Solution().findCircleNum([[1, 1, 0],
[1, 1, 0],
[0, 0, 1]]) == 2
assert Solution().findCircleNum([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]) == 3
assert Solution().findCircleNum([[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 1, 1, 1],
[1, 0, 1, 1]]) == 1
解题思路:下标作为节点,深搜标记能到达的,并添加到集合set,开始深搜次数即是结果
时间复杂度:O(n^2)
"""
n = len(isConnected)
flag = set()
# 深搜标记
def dfs(x: int):
flag.add(x)
for i in range(n):
if i in flag:
continue
if isConnected[x][i] == 1 or isConnected[i][x] == 1:
dfs(i)
result = 0
for i in range(n):
if i in flag:
continue
dfs(i)
result += 1
return result
使用数组下标优化下时间:
class Solution:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
"""
assert Solution().findCircleNum([[1, 1, 0],
[1, 1, 0],
[0, 0, 1]]) == 2
assert Solution().findCircleNum([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]) == 3
assert Solution().findCircleNum([[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 1, 1, 1],
[1, 0, 1, 1]]) == 1
解题思路:下标作为节点,深搜标记能到达的,并添加到集合set,开始深搜次数即是结果
时间复杂度:O(n^2)
"""
# 深搜标记
def dfs(x: int):
flag[x] = True
for i in range(n):
if not flag[i]:
if isConnected[x][i] == 1 or isConnected[i][x] == 1:
dfs(i)
n = len(isConnected)
flag = [False] * n
result = 0
for i in range(n):
if not flag[i]:
dfs(i)
result += 1
return result