题解 | #迷宫问题#

迷宫问题

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

import sys
#使用深度优先搜索算法,可以搜索出所有路径.
#向4个方向查找能否通行
#L是迷宫, stepL是路径
def dfs(L, x, y, stepL):
    #定义4个方向,右,下,左,上
    nexts = [[0,1], [1,0], [0,-1], [-1, 0]]
#     print(stepL)
    #到终点了
    if x == len(L) - 1 and y == len(L[0]) - 1:
#         print(stepL)
        for s in stepL:
            print("({},{})".format(s[0], s[1]))
        return
    #遍历4种走法
    for i in range(len(nexts)):
        tx = x + nexts[i][0]
        ty = y + nexts[i][1]
        if tx < 0 or tx >= len(L):
            continue
        if ty < 0 or ty >= len(L[0]):
            continue   
        #判断该点是否为障碍物或者已经在路径中
        if L[tx][ty] == 0 and [tx, ty] not in stepL:
            stepL.append([tx, ty])#添加到路径中,标记已经走过
            dfs(L, tx, ty, stepL)#下一步
            stepL.remove([tx, ty])#尝试结束,取消这个点的标记
    return 



while True:
    try:
        N,M = list(map(int, input().split()))
        L = []
        for n in range(N):
            L.append(list(map(int, input().split())))
#         print(L)
        stepL = [[0,0]]
        dfs(L, 0, 0, stepL)
    except:
#         print(sys.exc_info())
        break

















全部评论

相关推荐

强大的马里奥:不太可能,我校计算机硕士就业率99%
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务