题解 | #迷宫问题#

迷宫问题

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

'''
该递归方法在有多解时,会把所有解的路径返回出来,

因为每当有一个递归

到达目的地或者遇到死路时,递归会返回到岔路口地区
'''

while True:
    try:
        #构造迷宫
        m,n=list(map(int,input().split()))
        maze=[]
        for k in range(m):
            maze.append(list(map(int,input().split())))

        def step(i, j, pos=[(0,0)]):
            #看能否向下:
            if i+1<=m-1 and maze[i+1][j]==0 and (i+1,j) not in pos:
                step(i+1, j, pos+[(i+1,j)])  # 注意不能用pos.append()
            # 看能否向上:
            if i-1>=0 and  maze[i-1][j]==0 and (i-1,j) not in pos:
                step(i-1, j, pos+[(i-1,j)])
            # 看能否向右:
            if j+1<=n-1 and maze[i][j+1]==0 and (i,j+1)not in pos:
                step(i, j+1, pos+[(i,j+1)])
            # 看能否向左:
            if j-1>=0 and maze[i][j-1]==0 and (i,j-1) not in pos:
                step(i, j-1, pos+[(i,j-1)])
            if i==m-1 and j==n-1:
                for p in pos:
                    print('('+str(p[0])+','+str(p[1])+')')   # 注意不能用print(p)
        step(0,0)
    except:
        break

【牛客站内】华为机试题练习记录

全部评论
最后输出为啥这么写啊??
点赞 回复 分享
发布于 2022-06-02 22:09

相关推荐

SaviorSu:直接说下学期可以请假,一般情况学校允许我26届,大三就直接去实习了
点赞 评论 收藏
分享
10-31 13:04
南华大学 Java
嵌入式的小白:很多面试,面试前不会去打扰cto的,但一般cto不会在这些小事上刷人,只能说这个cto比较操心,啥重要不重要,紧急不紧急的,估计都会过问,平淡看待吧
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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