题解 | #迷宫问题#

迷宫问题

https://www.nowcoder.com/practice/cf24906056f4488c9ddb132f317e03bc

m,n = map(int,input().split())
grid = [list(map(int,input().split())) for _ in range(m)]
route = []
real_route = [] #记录最短路径
op = m*n #记录最短路径长度
def bfs(a,b,i,j):
    global op,real_route,route,grid
    if route: #当走错路回退时,利用上一步路对错路分支剪切
        route = route[:route.index((a,b))+1]
    route.append((i,j))
    if not 0<=i<m or not 0<=j<n:
        return
    if grid[i][j] ==1:
        return
    if i==m-1 and j ==n-1:
        if len(route)<op:
            real_route = route.copy()
            op = len(route)
        return
    grid[i][j] =1 #不走回头路
    bfs(i,j,i+1,j)
    bfs(i,j,i,j+1)
    bfs(i,j,i-1,j)
    bfs(i,j,i,j-1)
bfs(0,0,0,0) #前两个初始参数随意
for i in real_route:
    print('('+str(i[0])+','+str(i[1])+')')

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务