题目
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.
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
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)
Notice
source and destination must be empty.
Knight can not enter the barrier.
Path length refers to the number of steps the knight takes.
我的想法
典型的BFS层级遍历题。因为这里需要返回的是需要多少步,这个步数即层数
/**
* 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 {
public int shortestPath(boolean[][] grid, Point source, Point destination) {
Queue<Point> queue = new LinkedList<>();
int[] dircX = {1,1,-1,-1,2,2,-2,-2};
int[] dircY = {2,-2,2,-2,1,-1,1,-1};
queue.offer(source);
grid[source.x][source.y] = true;
int steps = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
Point cur = queue.poll();
//should pay attention to the relationship between
//determination of destination and the increase of steps
if(cur.x == destination.x && cur.y == destination.y) {
return steps;
}
for(int dirc = 0; dirc < 8; dirc++) {
Point newPoint = new Point(
cur.x + dircX[dirc],
cur.y + dircY[dirc]
);
if(!inBound(newPoint, grid) || grid[newPoint.x][newPoint.y] == true) {
continue;
}
queue.offer(newPoint);
grid[newPoint.x][newPoint.y] = true;
}
}
steps++;
}
return -1;
}
private boolean inBound(Point cur, boolean[][] grid) {
if(cur.x < 0 || cur.x >= grid.length || cur.y < 0 || cur.y >= grid[0].length) {
return false;
}
return true;
}
}
这种棋盘型题目也可以用DP来做,等学到DP再来补写吧~
解答
BFS & DP