Python算法之迷宫问题

Python算法之迷宫问题

问题:一个由0和1构成的二维数组中,假设1是可以移动到的点,0是不能移动到的点,如何从数组中间一个值为1的点出发,每一次只能朝上下左右四个方向移动一个单位,当二维数组的边缘,即可得到问题的解。这样的问题即是迷宫问题。

代码:

# 定义当前位置的四个偏移量
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
# 找到的路径
path = []


# 给迷宫maze的位置pos标“2”表示到过了
def mark(maze, pos):
    maze[pos[0]][pos[1]] = 2


# 检查迷宫maze的位置pos是否可通行
def passable(maze, pos):
    return maze[pos[0]][pos[1]] == 0


def find_path(maze, pos, end):
    mark(maze, pos)
    if pos == end:
        # 已到达出口,输出这个位置。成功结束
        print(pos, end=' ')
        path.append(pos)
        return True
    for i in range(4):  # 否则按四个方向顺序检查
        nextp = pos[0] + dirs[i][0], pos[1] + dirs[i][1]
        # 考虑一下可能的方向
        if passable(maze, nextp):  # 不可行的相邻位置不管
            if find_path(maze, nextp, end):
                # 如果从nextp可达出口,输出这个位置。成功结束
                print(pos, end=' ')
                path.append(pos)
                return True
    return False


def see_path(maze, path):  # 使寻找到的路径可视化
    for i, p in enumerate(path):
        if i == 0:
            maze[p[0]][p[1]] = 'E'
        elif i == len(path) - 1:
            maze[p[0]][p[1]] = 'S'
        else:
            maze[p[0]][p[1]] = 3
    print('
')
    for r in maze:
        for c in r:
            if c == 3:
                print('\033[0;31m' + "*" + " " + '\033[0m', end='')
            elif c == 'S' or c == 'E':
                print('\033[0;34m' + c + " " + '\033[0m', end='')
            elif c == 2:
                print('\033[0;32m' + "#" + " " + '\033[0m', end='')
            elif c == 1:
                print('\033[0;;40m' + " " * 2 + '\033[0m', end='')
            else:
                print(" " * 2, end="")
        print()


if __name__ == '__main__':
    maze = [
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1],
        [1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1],
        [1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1],
        [1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1],
        [1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1],
        [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1],
        [1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1],
        [1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    ]
    start = (1, 1)
    end = (10, 12)
    find_path(maze, start, end)
    see_path(maze, path)

运行结果:

(10, 12) (9, 12) (8, 12) (7, 12) (6, 12) (5, 12) (5, 11) (5, 10) 
(6, 10) (6, 9) (6, 8) (6, 7) (6, 6) (6, 5) (6, 4) (6, 3) 
(7, 3) (7, 2) (7, 1) (6, 1) (5, 1) (4, 1) (3, 1) (2, 1) (1, 1) 
Python算法之迷宫问题

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章