From 655a513b3145aef9d96db0cdc3983b47572d19cf Mon Sep 17 00:00:00 2001 From: zl127LiamLi <143149260+zl127LiamLi@users.noreply.github.com> Date: Sat, 9 Sep 2023 20:42:36 -0500 Subject: [PATCH] 841 python3 add BFS solution.md --- problems/0841.钥匙和房间.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/problems/0841.钥匙和房间.md b/problems/0841.钥匙和房间.md index 00156d4e..b4785d1b 100644 --- a/problems/0841.钥匙和房间.md +++ b/problems/0841.钥匙和房间.md @@ -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 + ```