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 destination cannot be reached.
source and destination must be empty.
Knight can not enter the barrier.
Path length refers to the number of steps the knight takes.
Problem Correction
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
Example 1:
Input:
[[0,0,0],
[0,0,0],
[0,0,0]]
source = [2, 0] destination = [2, 2]
Output: 2
Explanation:
[2,0]->[0,1]->[2,2]
Example 2:
Input:
[[0,1,0],
[0,0,1],
[0,0,0]]
source = [2, 0] destination = [2, 2]
Output:-1
思路:就是一个BFS;如果可以modify grid的话,就不需要hashset去记录visited point,直接标注成true就行了;return step如果是在外面,就是return step,如果是在下一层循环里面,就是step+1;
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
public class Solution {
/**
* @param grid: a chessboard included 0 (false) and 1 (true)
* @param source: a point
* @param destination: a point
* @return: the shortest path
*/
public int shortestPath(boolean[][] grid, Point source, Point destination) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
Queue<Point> queue = new LinkedList<Point>();
int n = grid.length;
int m = grid[0].length;
boolean[][] visited = new boolean[n][m];
queue.offer(source);
visited[source.x][source.y] = true;
int step = 0;
int[] dx = {1,1,-1,-1,2,2,-2,-2};
int[] dy = {2,-2,2,-2,1,-1,1,-1};
while(!queue.isEmpty()){
int size = queue.size();
while(size > 0) {
Point point = queue.poll();
size--;
if(point.x == destination.x && point.y == destination.y) {
return step;
}
for(int k = 0; k < 8; k++) {
int nx = point.x + dx[k];
int ny = point.y + dy[k];
if(isvalid(nx, ny, visited, grid)){
queue.offer(new Point(nx, ny));
visited[nx][ny] = true;
}
}
}
step++;
}
return -1;
}
private boolean isvalid(int nx, int ny, boolean[][] visited, boolean[][] grid) {
int n = grid.length;
int m = grid[0].length;
return (0 <= nx && nx < n && 0 <= ny && ny < m && !visited[nx][ny] && !grid[nx][ny]);
}
}