求knight从source 到destination的最短路径。采用bfs和dictionary,dictionary用来记录点到(x,y)的最短路径。
算法:首先把source放入queue中,并记录source对应路径为0,将source周围一步可以到达的点放入queue中,并记录他们的路径长度为1,继续上述操作,如果点超出矩阵或者矩阵对应点为1(barriar)或者已经走过此点,则跳过上述操作。最后如果queue中弹出的点是destination,则对应路径为最短路径。如果没有返回最短路径则说明到不了这点,则返回-1。
python代码:
class Solution:
"""
@param grid: a chessboard included 0 (false) and 1 (true)
@param source: a point
@param destination: a point
@return: the shortest path
"""
def shortestPath(self, grid, source, destination):
# write your code here
from collections import deque
delta = [[1, 2], [1, -2], [-1, 2], [-1, -2], [2, 1], [2, -1], [-2, 1], [-2, -1]]
dictionary = {(source.x, source.y): 0}
queue = deque()
queue.append([source.x, source.y])
while queue:
x, y = queue.popleft()
if (x, y) == (destination.x, destination.y):
return dictionary[(x, y)]
for delta_x, delta_y in delta:
newx = x + delta_x
newy = y + delta_y
if newx < 0 or newx >= len(grid) or newy < 0 or newy >= len(grid[0]):
continue
if grid[newx][newy] == 1:
continue
if (newx, newy) in dictionary:
continue
queue.append([newx, newy])
dictionary[(newx, newy)] = dictionary[(x, y)] + 1
return -1
网友评论