611.Knight Shortest Path
1.Description(Medium)
Given a knight in a chessboard (a binary matrix with0as empty and1as barrier) with asourceposition, find the shortest path to adestinationposition, return the length of the route.
Return-1if knight can not reached.
国际象棋棋盘中骑士只能走对角线。
Notice
source and destination must be empty. Knight can not enter the barrier.
Clarification
If the knight is at (x,y), he can get to the following positions in one step:
(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)Example
[[0,0,0],
[0,0,0],
[0,0,0]]
source = [2, 0] destination = [2, 2] return 2
[[0,1,0],
[0,0,0],
[0,0,0]]
source = [2, 0] destination = [2, 2] return 6
[[0,1,0],
[0,0,1],
[0,0,0]]
source = [2, 0] destination = [2, 2] return -12.Code
即BFS找了几层找到了destination
所以加一个size记录当前level,每次遍历完当前level+1;
记得每次走到一个点就把0变成1,因为这样可以避免走重复的路。
如果此题grid中没有障碍,则不需要那个判断inBound
因为是计算步数,所以要加上size来记录step数
Last updated
Was this helpful?