关于一道bfs的起点选择顺序

题目来自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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值