mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 07:35:35 +08:00
841 python3 add BFS solution.md
This commit is contained in:
@ -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
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user