python 求迷宫最短路径

杀马特。学长 韩版系。学妹 提交于 2020-02-26 19:14:27

##输入n行m列的矩阵,1为可通行,0为障碍,求左上角到右下角的最短路径
###输入
6 5
1 1 0 1 1
1 0 1 1 1
1 0 1 0 0
1 0 1 1 1
1 1 1 0 1
1 1 1 1 1
###输出
9

import queue

pic = []
dis = []
visited = []
nx = [[1, 0], [-1, 0], [0, -1], [0, 1]]

class Node():
    def __init__(self, x, y):
        self.x = x
        self.y = y

def bfs():
    dis[0][0] = 0
    q = queue.Queue()
    node = Node(0,0)
    q.put(node)
    while q.qsize():
        point = q.get()
        if point.x == n-1 and point.y == m-1:
            break
        for i in range(4):
            dx = point.x + nx[i][0]
            dy = point.y + nx[i][1]
            if (0 <= dx < n and 0 <= dy < m and pic[dx][dy] == 1):
                newPoint = Node(dx, dy)
                q.put(newPoint)
                dis[dx][dy] = dis[point.x][point.y] + 1

n, m = map(int, input().split())
for i in range(n):
    temp = list(map(int, input().split()))
    pic.append(temp)
dis = [[float('inf') for i in range(m)] for i in range(n)]

bfs()
print(dis[n-1][m-1])

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!