Knight Shortest Path

update Jul 19, 2017 10:50

liintcodearrow-up-right

Given a knight in a chessboard (a binary matrix with 0 as empty and 1 as barrier) with a source position, find the shortest path to a destination position, return the length of the route. Return -1 if knight can not reached.

Notice

source and destination must be empty. Knight can not enter the barrier.

Have you met this question in a real interview? Yes 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 -1

Basic Idea:

基本思想就是做分层BFS,每层就是每步。值得注意的是对dx dy坐标变换数组的进一步应用。

加速的解法是从source和destination两个点同时开始bfs,这就是传说中的双向广度优先搜索算法。其中有一些细节需要注意。 1. 双向BFS由于搜索深度减半,可以获得相当于普通BFS开根号级别的时间复杂度。 2. 要注意双向BFS是双向逐层搜索,所以是每次搜索一个队列中的全部节点。 3. 需要注意奇偶不同的边界条件(参考下面的实现)。 4. 当一方队列为空时,如果仍未找到,则说明搜索失败了。

Java Implementation:

  • 普通BFS

  • 双向BFS

Update C++ Solution

要记得在入队之后马上标记,不可以等到出队时再标记,否则会出现多次入队的情况。