def dfs(grid, visited, row, col, m, n):
# 判断当前位置是否合法
if row < 0 or col < 0 or row >= m or col >= n or grid[row][col] == 1 or visited[row][col]:
return False
# 标记当前位置为已访问
visited[row][col] = True
# 判断是否到达终点
if row == m-1 and col == n-1:
return True
# 递归搜索四个方向
if dfs(grid, visited, row+1, col, m, n) or dfs(grid, visited, row-1, col, m, n) or dfs(grid, visited, row, col+1, m, n) or dfs(grid, visited, row, col-1, m, n):
return True
#CYH_Hang精品
# 如果四个方向都不能到达终点,则返回False
return False
def find_path(grid):
if not grid or not grid[0]:
return False
m, n = len(grid), len(grid[0])
# 创建一个visited数组来记录访问状态
visited = [[False for _ in range(n)] for _ in range(m)]
return dfs(grid, visited, 0, 0, m, n)
使用dfs实现机器人寻路Python代码
最新推荐文章于 2024-08-29 16:57:08 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)