1.题目描述
给定一个n*m的二维整数数组,用来表示一个迷宫,数组中只包含0或1,其中0表示可以走的路,1表示不可通过的墙壁。
最初,有一个人位于左上角(1, 1)处,已知该人每次可以向上、下、左、右任意一个方向移动一个位置。
请问,该人从左上角移动至右下角(n, m)处,至少需要移动多少次。
数据保证(1, 1)处和(n, m)处的数字为0,且一定至少存在一条通路。
输入格式
第一行包含两个整数n和m。
接下来n行,每行包含m个整数(0或1),表示完整的二维数组迷宫。
输出格式
输出一个整数,表示从左上角移动至右下角的最少移动次数。
数据范围
1≤n,m≤1001≤n,m≤100
输入样例:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出样例:
8
题目来源:https://www.acwing.com/problem/content/846/
2.解题思路
1,起始点坐标加入队列,设置距离为0
2,while 队列不为空,队头出队一个节点,如果这个节点的上/下/左/右可以到达(不碰壁、不超过边界,之前未被访问),则把能到达的加入队列,距离+1
3,如果到达终点,返回距离
3.代码实现
import sys
n, m = map(int, sys.stdin.readline().strip().split())
A = []
for i in range(n):
A.append(list(map(int, sys.stdin.readline().strip().split())))
# visited初始化
vis = [[False for j in range(m)] for i in range(n)]
vis[0][0] = True
que = []
# 加入的是这个节点的元组表示(x,y,距离)
que.append((0, 0, 0))
# 四个方向
dx=[-1,0,1,0]
dy=[0,-1,0,1]
while len(que) != 0:
x, y, c = que.pop(0)
# 出口,到达终点
if x == n-1 and y == m-1:
print c
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
if nx >= 0 and nx < n and ny >= 0 and ny < m and A[nx][ny] == 0 and vis[nx][ny]==False:
que.append((nx, ny, c + 1))
vis[nx][ny] = True