只有一条路径走得通为什么还要说求最短路径,而且只有一条路径走得通也让大家可以投机取巧,不用广度、深度优先搜索就能出结果(看已通过的代码);
附上广度优先搜索找最短路径代码(适用真正的多路径找最短问题):
def bfs(maze,x1,y1,x2,y2):
directions = [(1,0),(-1,0),(0,1),(0,-1)]
queue = [(x1,y1,-1)]
path = []
while queue:
path.append(queue.pop(0))
cur = (path[-1][0],path[-1][1])
if cur == (x2,y2):
res = [(path[-1][0],path[-1][1])]
loc = path[-1][2]
while loc != -1:
res.append((path[loc][0],path[loc][1]))
loc = path[loc][2]
return res
for d in directions:
next_node = (cur[0]+d[0],cur[1]+d[1])
if 0 <= next_node[0] < len(maze) and \
0 <= next_node[1] < len(maze[0]) and \
maze[next_node[0]][next_node[1]] == 0:
maze[next_node[0]][next_node[1]] == 2
queue.append((next_node[0],next_node[1],len(path)-1))
while True:
try:
m,n = list(map(int, input().split()))
maze = []
for i in range(m):
maze.append(list(map(int, input().split())))
res = bfs(maze, 0, 0, m-1, n-1)[::-1]
for i in res:
print('(%d,%d)'%(i[0],i[1]))
except:
break


京公网安备 11010502036488号