mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #2277 from zl127LiamLi/patch-1
841 python3 add BFS solution.md
This commit is contained in:
@ -324,7 +324,7 @@ class Solution {
|
|||||||
### python3
|
### python3
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
# 深度搜索优先
|
||||||
class Solution:
|
class Solution:
|
||||||
def dfs(self, key: int, rooms: List[List[int]] , visited : List[bool] ) :
|
def dfs(self, key: int, rooms: List[List[int]] , visited : List[bool] ) :
|
||||||
if visited[key] :
|
if visited[key] :
|
||||||
@ -346,6 +346,31 @@ class Solution:
|
|||||||
return False
|
return False
|
||||||
return True
|
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