5×6网格python迷宫
作者:野牛程序员:2023-07-15 17:48:32python阅读 2773
以下是一个使用 Python 编写的 5x6 网格迷宫的示例代码:
maze = [
[1, 0, 1, 1, 1, 1],
[1, 0, 1, 0, 0, 1],
[1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 0, 1],
]
def solve_maze(maze):
rows = len(maze)
cols = len(maze[0])
start = (0, 0)
end = (rows - 1, cols - 1)
path = []
visited = set()
def is_valid_move(row, col):
if 0 <= row < rows and 0 <= col < cols and maze[row][col] == 1 and (row, col) not in visited:
return True
return False
def dfs(row, col):
if (row, col) == end:
return True
visited.add((row, col))
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for dx, dy in directions:
new_row = row + dx
new_col = col + dy
if is_valid_move(new_row, new_col):
path.append((new_row, new_col))
if dfs(new_row, new_col):
return True
path.pop()
return False
if dfs(start[0], start[1]):
path.append(start)
path.reverse()
return path
else:
return None
solution = solve_maze(maze)
if solution:
print("迷宫的解路径为:")
for row, col in solution:
print(f"({row}, {col})")
else:
print("迷宫没有解路径。")该代码使用深度优先搜索算法来解决迷宫问题。迷宫表示为一个二维列表,其中1表示可以通过的路径,0表示障碍物。算法从起点开始,在每个可以移动的位置进行递归搜索,直到找到终点或无法继续移动为止。如果找到了解路径,它将打印出路径上的所有坐标。否则,它将输出 "迷宫没有解路径。"
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:如何用python画图
- 下一篇:python制作图形化界面
