Description
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.
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
5/13/2017
算法班,未经验证
1 /** 2 * Definition for a point. 3 * public class Point { 4 * publoc int x, y; 5 * public Point() { x = 0; y = 0; } 6 * public Point(int a, int b) { x = a; y = b; } 7 * } 8 */ 9 public class Solution { 10 /** 11 * @param grid a chessboard included 0 (false) and 1 (true) 12 * @param source, destination a point 13 * @return the shortest path 14 */ 15 public int shortestPath(boolean[][] grid, Point source, Point destination) { 16 // Write your code here 17 if (grid == null || grid.length == 0 || grid[0].length == 0) { 18 return -1; 19 } 20 if (grid[destination.x][destination.y] == 1 || grid[source.x][source.y] == 1) { 21 return -1; 22 } 23 int[] xDirection = new int[]{1, 1, -1, -1, 2, 2, -2, -2}; 24 int[] yDirection = new int[]{2, -2, 2, -2, 1, -1, 1, -1}; 25 26 Queue<Point> queue = new LinkedList<Point>(); 27 28 boolean[][] visited = new boolean[grid.length][grid[0].length]; 29 int count = 0; 30 31 queue.offer(source); 32 33 while (!queue.isEmpty()) { 34 Point p = queue.poll(); 35 if (p.x == destination.x && p.y == destination.y) return count; 36 37 if (visited[p.x][p.y] || grid[p.x][p.y]) continue; 38 visited[p.x][p.y] = true; 39 40 for (int i = 0; i < xDirection.length; i++) { 41 int tmpX = p.x + xDirection[i]; 42 int tmpY = p.y + yDirection[i]; 43 if (!outOfBoundary(tmpX, tmpY, grid.length, grid[0].length)) { 44 queue.offer(new Pont(tmpX, tmpY)); 45 } 46 } 47 count++; 48 } 49 return -1; 50 } 51 private boolean outOfBoundary(int x, int y, int xLength, int yLength) { 52 if (x >= xLength || x < 0 || y >= yLength || y < 0) return true; 53 return false; 54 } 55 }