题目来自acwing1076. 迷宫问题
这题用bfs,但是问题在于要记录路径,刚开始我就疑惑这样怎么能保证一定是最段的一条能,从起点到中点每一条路径都会记录(如一),后来发现了其实只要反过来,从终点到起点,把路径记录也反过来用下一步点的位置记录上一步点位(靠近起点的做下标)就好了呀(如二)。
(一)
dx=[0,0,1,-1]
dy=[1,-1,0,0]
n=int(input())
mp=[]
for i in range(n):
s=list(map(int,input().split()))
mp.append(s)
ans=0
q=[]
record = dict()
q.append((0,0))
mp[0][0]=1
while(len(q)>0):
now = q.pop(0)
for i in range(4):
nx = now[0] + dx[i]
ny = now[1] + dy[i]
if (ny >= 0 and ny < n and nx >= 0 and nx < n and mp[nx][ny]==0):
q.append((nx,ny))
mp[nx][ny]=1
record[(now[0],now[1])]=(nx,ny)
loc = (0,0)
print('0 0')
while loc != (n-1, n-1):
# a=map(str,record[loc])
# b=str(record[loc])
print(' '.join(map(str,record[loc])))
loc = record[loc]
(二)
dx=[0,0,1,-1]
dy=[1,-1,0,0]
n=int(input())
mp=[]
for i in range(n):
s=list(map(int,input().split()))
mp.append(s)
ans=0
q=[]
record = dict()
q.append((n-1,n-1))
mp[n-1][n-1]=1
while(len(q)>0):
now = q.pop(0)
for i in range(4):
nx = now[0] + dx[i]
ny = now[1] + dy[i]
if (ny >= 0 and ny < n and nx >= 0 and nx < n and mp[nx][ny]==0):
q.append((nx,ny))
mp[nx][ny]=1
record[(nx,ny)]=(now[0],now[1])
loc = (0,0)
print('0 0')
while loc != (n-1, n-1):
print(' '.join(map(str,record[loc])))
loc = record[loc]