Lintcode: Knight Shortest Path

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 destinationposition, 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.

 
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

 BFS solution:

 1 package fbOnsite;
 2 
 3 import java.util.*;
 4 
 5 public class KnightShortestPath {
 6     public static int shortestPath(int[][] board, int[] src, int[] dst) {
 7         int[][] directions = new int[][]{{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
 8         int m = board.length;
 9         int n = board[0].length;
10         int res = 0;
11         
12         Queue<Integer> queue = new LinkedList<Integer>();
13         HashSet<Integer> visited = new HashSet<Integer>();
14         queue.offer(src[0]*n + src[1]);
15         while (!queue.isEmpty()) {
16             int size = queue.size();
17             for (int i=0; i<size; i++) {
18                 int cur = queue.poll();
19                 visited.add(cur);
20                 int x = cur / n;
21                 int y = cur % n;
22                 if (x == dst[0] && y == dst[1]) return res;
23                 
24                 for (int[] dir : directions) {
25                     int nx = x + dir[0];
26                     int ny = y + dir[1];
27                     if (nx<0 || nx>=m || ny<0 || ny>=n || visited.contains(nx*n+ny) || board[nx][ny]!=0)
28                         continue;
29                     queue.offer(nx*n + ny);
30                 }
31             }
32             res++;
33         }
34         return res;
35     }
36     
37     
38 
39     /**
40      * @param args
41      */
42     public static void main(String[] args) {
43         // TODO Auto-generated method stub
44         int[][] board = new int[][] {{0,1,0},{0,0,0},{0,0,0}};
45         int[] src = new int[]{2,0};
46         int[] dst = new int[]{2,2};
47         int res = shortestPath(board, src, dst);
48         System.out.println(res);
49     }
50 
51 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/6546118.html