##输入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])
来源:CSDN
作者::)Lakers_yw
链接:https://blog.csdn.net/weixin_42807492/article/details/104521315