Skip to content

Commit d846efe

Browse files
committed
广度优先遍历和深度优先遍历
1 parent 49e8489 commit d846efe

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

search/841_canVisitAllRooms.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import collections
2+
from typing import List
3+
4+
5+
class Solution:
6+
def canVisitAllRooms_bfs(self, rooms: List[List[int]]) -> bool:
7+
n = len(rooms)
8+
vis = {0}
9+
q = collections.deque()
10+
q.append(0)
11+
num = 0
12+
13+
while q:
14+
x = q.popleft()
15+
num += 1
16+
17+
for i in rooms[x]:
18+
if i not in vis:
19+
vis.add(i)
20+
q.append(i)
21+
22+
return num == n
23+
24+
def canVisitAllRooms_dfs(self, rooms: List[List[int]]) -> bool:
25+
def dfs(x):
26+
vis.add(x)
27+
nonlocal num
28+
num += 1
29+
for it in rooms[x]:
30+
if it not in vis:
31+
dfs(it)
32+
33+
n = len(rooms)
34+
vis = set()
35+
num = 0
36+
dfs(0)
37+
return n == num

0 commit comments

Comments
 (0)