以下是一个基本的走迷宫的代码示例:

maze = [[0,0,0,0,0],
        [1,1,0,1,0],
        [0,0,0,1,0],
        [0,1,1,1,0],
        [0,0,0,0,0]]

def solve_maze(maze, start, end):
    directions = [(0,1), (0,-1), (1,0), (-1,0)]
    visited = set()
    queue = [(start, [])]
    
    while queue:
        current, path = queue.pop(0)
        if current == end:
            return path + [current]
        visited.add(current)
        for direction in directions:
            next_pos = (current[0] + direction[0], current[1] + direction[1])
            if next_pos[0] < 0 or next_pos[0] >= len(maze) or next_pos[1] < 0 or next_pos[1] >= len(maze[0]):
                continue
            if maze[next_pos[0]][next_pos[1]] == 1 or next_pos in visited:
                continue
            queue.append((next_pos, path + [current]))
            
    return None

start = (0,0)
end = (4,4)
path = solve_maze(maze, start, end)

if path:
    print('Path found:', path)
else:
    print('No path found.')

这个代码使用了广度优先搜索算法来找到迷宫中的路径。它首先将起点加入一个队列中,然后不断从队列中取出位置,并将它的相邻位置加入队列中。如果队列中的位置是终点,那么就返回路径。如果队列为空,那么就说明没有找到路径。

迷宫求解算法:Python代码示例

原文地址: https://www.cveoy.top/t/topic/jsD6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录