DFS这题和LC200很相似,但是岛屿是二维的,而这个只算一维的,因为行数和列数都是省份的数量,1表示两个省份是否连接。所以这一题需要注意的就是把它用一维的思想进行处理
def findCircleNum(self, isConnected):
"""
:type isConnected: List[List[int]]
:rtype: int
"""
visited = set()
cities = len(isConnected)
count = 0
def dfs(i):
for j in range(cities):
if isConnected[i][j] == 1 and j not in visited:
visited.add(j)
dfs(j)
for i in range(cities):
if i not in visited:
visited.add(i)
dfs(i)
count += 1
return count
BFS
def findCircleNum(self, isConnected):
"""
:type isConnected: List[List[int]]
:rtype: int
"""
n = len(isConnected)
visited = set()
count = 0
for i in range(n):
if i not in visited:
queue = deque([i])
while queue:
i = queue.popleft()
for j in range(n):
if isConnected[i][j] == 1 and j not in visited:
queue.append(j)
visited.add(j)
count += 1
return count