Given a knight in a chessboard n * m
(a binary matrix with 0 as empty and 1 as barrier). the knight initialze position is (0, 0)
and he wants to reach position (n - 1, m - 1)
, Knight can only be from left to right. Find the shortest path to the destination position, return the length of the route. Return -1
if knight can not reached.
Example
Example 1:
Input:
[[0,0,0,0],[0,0,0,0],[0,0,0,0]]
Output:
3
Explanation:
[0,0]->[2,1]->[0,2]->[2,3]
Example 2:
Input:
[[0,1,0],[0,0,1],[0,0,0]]
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 + 2, y + 1)
(x - 2, y + 1)
思路:唯一要注意的是,从列开始写循环,不能从行开始写,否则会出错,应该是y一直在增加;
public class Solution {
/**
* @param grid: a chessboard included 0 and 1
* @return: the shortest path
*/
public int shortestPath2(boolean[][] grid) {
if(grid == null || grid.length == 0) {
return -1;
}
int n = grid.length;
int m = grid[0].length;
int[][] dp = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
dp[i][j] = Integer.MAX_VALUE;
}
}
dp[0][0] = 0;
// 坐标是move的镜像,也就是x,y从这些点来的;
int[] dx = {2, 1,-1,-2};
int[] dy = {-1,-2,-2,-1};
// tricky的地方,是首先写列的循环,否则通不过,因为只是往右走,y++;
for(int j = 0; j < m; j++){
for(int i = 0; i < n; i++) {
if(!grid[i][j]) {
for(int k = 0; k < 4; k++) {
int nx = i + dx[k];
int ny = j + dy[k];
if(0 <= nx && nx < n && 0 <= ny && ny < m &&
dp[nx][ny] != Integer.MAX_VALUE)
dp[i][j] = Math.min(dp[i][j], dp[nx][ny] + 1);
}
}
}
}
if(dp[n-1][m-1] == Integer.MAX_VALUE) {
return -1;
}
return dp[n-1][m-1];
}
}