diff --git a/problems/图论广搜理论基础.md b/problems/图论广搜理论基础.md index 1174e239..b631f4f5 100644 --- a/problems/图论广搜理论基础.md +++ b/problems/图论广搜理论基础.md @@ -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 # 标记为访问过的节点 + +``` +