题解 | #迷宫问题#有没有人帮我看看第四行的问题

迷宫问题

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

# 深度搜索dfs 会返回所有的路径,然后用一个数组保存这些路径,再找到最少的
def DFS(x,y):
    if x == row-1 and y == col - 1:
        temp.extend(route) #不知道 为什么temp.append(route)不行,只保存第一个项
        return 
    
    for i,j in [[0,-1],[0,1],[-1,0],[1,0]]:
        temp_x = x+i
        temp_y = y+j
        if temp_x in range(row) and temp_y in range(col) and maze[temp_x][temp_y] == '0':
            maze[temp_x][temp_y] = '1'
            temp1 = []
            temp1.append(temp_x)
            temp1.append(temp_y)
            route.append(temp1)
            DFS(temp_x,temp_y)
            maze[temp_x][temp_y] = '0'
            route.pop() 
    else:
        return         
    

row,col = [int(x) for x in input().split(' ')]
maze = []
temp = []
for i in range(row):
    maze.append([x for x in input().split(' ')])
route = [[0,0]]
DFS(0,0)

count = 1
res = temp
tag = 0
for i in range(1,len(temp)):
    if temp[i] == [0,0]:
        tag = i
        if count < len(res):
            res = temp[i-count:i]
        count = 1
    elif i == len(temp)-1:
        if i- tag +1 < len(res):
            res = temp[tag:]
    else:
        count += 1

for i in res:
    print(f"({i[0]},{i[1]})")


#悬赏#
全部评论
route(一个二位数组[[ ]])保存的是到达结尾是走过的路径,但不知道为什么list.append(route)的时候,只添加了第一个元素
点赞 回复 分享
发布于 2024-03-21 20:34 湖北

相关推荐

不讲武德的候选人很能...:把中北改成中南,试一下😂
简历被挂麻了,求建议
点赞 评论 收藏
分享
08-08 11:51
门头沟学院 Java
点赞 评论 收藏
分享
06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
08-07 11:41
安徽大学 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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