Skip to content

Commit 3d9fa89

Browse files
Merge pull request youngyangyang04#2309 from Logenleedev/my-contribution
add python 模版
2 parents 24201c2 + 0cc023d commit 3d9fa89

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,9 @@ 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+
113116
## 总结
114117

115118
当然广搜还有很多细节需要注意的地方,后面我会针对广搜的题目还做针对性的讲解,因为在理论篇讲太多细节,可能会让刚学广搜的录友们越看越懵,所以细节方面针对具体题目在做讲解。
@@ -122,6 +125,37 @@ if (!visited[nextx][nexty] && grid[nextx][nexty] == '1') { // 如果节点没被
122125

123126
相信看完本篇,大家会对广搜有一个基础性的认识,后面再来做对应的题目就会得心应手一些。
124127

128+
## 其他语言版本
129+
130+
### Python
131+
```python
132+
from collections import deque
133+
134+
dir = [(0, 1), (1, 0), (-1, 0), (0, -1)] # 创建方向元素
135+
136+
def bfs(grid, visited, x, y):
137+
138+
queue = deque() # 初始化队列
139+
queue.append((x, y)) # 放入第一个元素/起点
140+
visited[x][y] = True # 标记为访问过的节点
141+
142+
while queue: # 遍历队列里的元素
143+
144+
curx, cury = queue.popleft() # 取出第一个元素
145+
146+
for dx, dy in dir: # 遍历四个方向
147+
148+
nextx, nexty = curx + dx, cury + dy
149+
150+
if nextx < 0 or nextx >= len(grid) or nexty < 0 or nexty >= len(grid[0]): # 越界了,直接跳过
151+
continue
152+
153+
if not visited[nextx][nexty]: # 如果节点没被访问过
154+
queue.append((nextx, nexty)) # 加入队列
155+
visited[nextx][nexty] = True # 标记为访问过的节点
156+
157+
```
158+
125159

126160
<p align="center">
127161
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
 (0)