mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #2309 from Logenleedev/my-contribution
add python 模版
This commit is contained in:
@ -110,6 +110,9 @@ if (!visited[nextx][nexty] && grid[nextx][nexty] == '1') { // 如果节点没被
|
||||
```
|
||||
就可以通过 [200.岛屿数量](https://leetcode.cn/problems/number-of-islands/solution/by-carlsun-2-n72a/) 这道题目,大家可以去体验一下。
|
||||
|
||||
|
||||
|
||||
|
||||
## 总结
|
||||
|
||||
当然广搜还有很多细节需要注意的地方,后面我会针对广搜的题目还做针对性的讲解,因为在理论篇讲太多细节,可能会让刚学广搜的录友们越看越懵,所以细节方面针对具体题目在做讲解。
|
||||
@ -122,6 +125,37 @@ if (!visited[nextx][nexty] && grid[nextx][nexty] == '1') { // 如果节点没被
|
||||
|
||||
相信看完本篇,大家会对广搜有一个基础性的认识,后面再来做对应的题目就会得心应手一些。
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
### Python
|
||||
```python
|
||||
from collections import deque
|
||||
|
||||
dir = [(0, 1), (1, 0), (-1, 0), (0, -1)] # 创建方向元素
|
||||
|
||||
def bfs(grid, visited, x, y):
|
||||
|
||||
queue = deque() # 初始化队列
|
||||
queue.append((x, y)) # 放入第一个元素/起点
|
||||
visited[x][y] = True # 标记为访问过的节点
|
||||
|
||||
while queue: # 遍历队列里的元素
|
||||
|
||||
curx, cury = queue.popleft() # 取出第一个元素
|
||||
|
||||
for dx, dy in dir: # 遍历四个方向
|
||||
|
||||
nextx, nexty = curx + dx, cury + dy
|
||||
|
||||
if nextx < 0 or nextx >= len(grid) or nexty < 0 or nexty >= len(grid[0]): # 越界了,直接跳过
|
||||
continue
|
||||
|
||||
if not visited[nextx][nexty]: # 如果节点没被访问过
|
||||
queue.append((nextx, nexty)) # 加入队列
|
||||
visited[nextx][nexty] = True # 标记为访问过的节点
|
||||
|
||||
```
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
|
Reference in New Issue
Block a user