解题思路:
注意事项:
用DFS时间会超限,主要是回溯部分时间复杂度太高,BFS更适合本题多路径的思路
参考代码:
def bfs(): global map_, visited, dxdy, n, m, go, stack while stack: temp = stack.pop(0) for i, j, k in dxdy: if map_[temp[0] + i][temp[1] + j] == 0 and \ visited[temp[0] + i][temp[1] + j] is False: stack.append((temp[0] + i, temp[1] + j, temp[2] + 1)) visited[temp[0] + i][temp[1] + j] = True go[temp[0] + i][temp[1] + j] = go[temp[0]][temp[1]] + k if temp[0] + i == n and temp[1] + j == m: return go[-2][-2] n, m = map(int, input().split()) map_ = [[1 for _ in range(m + 2)]] visited = [[False for _ in range(m + 2)] for _ in range(n + 2)] visited[1][1], x, y = True, 1, 1 dxdy = [[1, 0, 'D'], [0, -1, 'L'], [0, 1, 'R'], [-1, 0, 'U']] go = [['' for _ in range(m + 2)] for _ in range(n + 2)] for i in range(n): map_.append([1] + list(map(int, input())) + [1]) map_.append([1 for _ in range(m + 2)]) stack = [(x, y, 0)] aa = bfs() print(len(aa)) print(aa, sep='')
0.0分
1 人评分