Knight Shortest Path II

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];
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值