Skip to content

Commit a78f677

Browse files
committed
add python 模版
1 parent be11452 commit a78f677

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

problems/图论广搜理论基础.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,38 @@ if (!visited[nextx][nexty] && grid[nextx][nexty] == '1') { // 如果节点没被
110110
```
111111
就可以通过 [200.岛屿数量](https://leetcode.cn/problems/number-of-islands/solution/by-carlsun-2-n72a/) 这道题目,大家可以去体验一下。
112112

113+
## 其他语言版本
114+
115+
### Python
116+
```python
117+
from collections import deque
118+
119+
dir = [(0, 1), (1, 0), (-1, 0), (0, -1)] # 创建方向元素
120+
121+
def bfs(grid, visited, x, y):
122+
123+
queue = deque() # 初始化队列
124+
queue.append((x, y)) # 放入第一个元素/起点
125+
visited[x][y] = True # 标记为访问过的节点
126+
127+
while queue: # 遍历队列里的元素
128+
129+
curx, cury = queue.popleft() # 取出第一个元素
130+
131+
for dx, dy in dir: # 遍历四个方向
132+
133+
nextx, nexty = curx + dx, cury + dy
134+
135+
if nextx < 0 or nextx >= len(grid) or nexty < 0 or nexty >= len(grid[0]): # 越界了,直接跳过
136+
continue
137+
138+
if not visited[nextx][nexty]: # 如果节点没被访问过
139+
queue.append((nextx, nexty)) # 加入队列
140+
visited[nextx][nexty] = True # 标记为访问过的节点
141+
142+
```
143+
144+
113145
## 总结
114146

115147
当然广搜还有很多细节需要注意的地方,后面我会针对广搜的题目还做针对性的讲解,因为在理论篇讲太多细节,可能会让刚学广搜的录友们越看越懵,所以细节方面针对具体题目在做讲解。

0 commit comments

Comments
 (0)