Merge pull request #2277 from zl127LiamLi/patch-1

841 python3 add BFS solution.md
This commit is contained in:
程序员Carl
2023-09-21 11:28:26 +08:00
committed by GitHub

View File

@ -324,7 +324,7 @@ class Solution {
### python3
```python
# 深度搜索优先
class Solution:
def dfs(self, key: int, rooms: List[List[int]] , visited : List[bool] ) :
if visited[key] :
@ -346,6 +346,31 @@ class Solution:
return False
return True
# 广度搜索优先
class Solution:
def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
visited = [False] * len(rooms)
self.bfs(rooms, 0, visited)
for room in visited:
if room == False:
return False
return True
def bfs(self, rooms, index, visited):
q = collections.deque()
q.append(index)
visited[0] = True
while len(q) != 0:
index = q.popleft()
for nextIndex in rooms[index]:
if visited[nextIndex] == False:
q.append(nextIndex)
visited[nextIndex] = True
```