LeetCode 547. Number of Provinces
考点 | 难度 |
---|---|
DFS | Medium |
题目
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.
思路
按行iterate matrix, 如果这一行代表的node没有seen过, 加到tosee list里。对于toosee list, 先pop出一个node判断有没有seen过, 然后iterate matrix里这个node的行, 如果位置上是1就把y坐标加到tosee
答案
class Solution(object):
def findCircleNum(self, M):
seen = set([])
res = 0
for i in range(len(M)):
if i not in seen:
toSee = [i]
while len(toSee):
cur = toSee.pop()
if cur not in seen:
seen.add(cur)
toSee = [j for j,v in enumerate(M[cur]) if v and j not in seen] + toSee
res += 1
return res