题解 | #迷宫问题#

迷宫问题

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

def directions(x,y,path):
    poss_dire = []
    if 0 <= x + 1 < a and 0 <= y < b and not (x+1,y) in path and Maze[x+1][y] == 0:
        poss_dire.append((x+1,y))
    if 0 <= x - 1 < a and 0 <= y < b and not (x-1,y) in path and Maze[x-1][y] == 0:
        poss_dire.append((x-1,y))
    if 0 <= x < a and 0 <= y + 1 < b and not (x,y+1) in path and Maze[x][y+1] == 0:
        poss_dire.append((x,y+1))
    if 0 <= x < a and 0 <= y - 1 < b and not (x,y-1) in path and Maze[x][y-1] == 0:
        poss_dire.append((x,y-1))
    return poss_dire

def myfunc(poss_dire,path_temp):
    global count
    if len(poss_dire) > 0 and count == 0:
        for dire in poss_dire:
            if dire == (a-1,b-1):
                Path = path_temp.copy()+[dire]
                count += 1
                for ijk in Path:
                    print(str(ijk).replace(' ', ''))
            else:
                m, n = dire[0], dire[1]
                k = directions(m,n,path_temp)
                myfunc(k,path_temp.copy()+[dire])

while True:
    try:
        a, b = map(int, input().split())
        count = 0
        Maze = []
        Path = []
        for _ in range(a):
            Maze.append(list(map(int, input().split())))
        Path.append((0,0))
        dires = directions(0,0,Path)
        myfunc(dires,Path)
#        for i in Path:
#            print(i)
    except:
        break
全部评论

相关推荐

牛客279957775号:铁暗恋
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务