Lintcode: Knight Shortest Path

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 destinationposition, 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

 BFS solution:

 1 package fbOnsite;
 2 
 3 import java.util.*;
 4 
 5 public class KnightShortestPath {
 6     public static int shortestPath(int[][] board, int[] src, int[] dst) {
 7         int[][] directions = new int[][]{{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
 8         int m = board.length;
 9         int n = board[0].length;
10         int res = 0;
11         
12         Queue<Integer> queue = new LinkedList<Integer>();
13         HashSet<Integer> visited = new HashSet<Integer>();
14         queue.offer(src[0]*n + src[1]);
15         while (!queue.isEmpty()) {
16             int size = queue.size();
17             for (int i=0; i<size; i++) {
18                 int cur = queue.poll();
19                 visited.add(cur);
20                 int x = cur / n;
21                 int y = cur % n;
22                 if (x == dst[0] && y == dst[1]) return res;
23                 
24                 for (int[] dir : directions) {
25                     int nx = x + dir[0];
26                     int ny = y + dir[1];
27                     if (nx<0 || nx>=m || ny<0 || ny>=n || visited.contains(nx*n+ny) || board[nx][ny]!=0)
28                         continue;
29                     queue.offer(nx*n + ny);
30                 }
31             }
32             res++;
33         }
34         return res;
35     }
36     
37     
38 
39     /**
40      * @param args
41      */
42     public static void main(String[] args) {
43         // TODO Auto-generated method stub
44         int[][] board = new int[][] {{0,1,0},{0,0,0},{0,0,0}};
45         int[] src = new int[]{2,0};
46         int[] dst = new int[]{2,2};
47         int res = shortestPath(board, src, dst);
48         System.out.println(res);
49     }
50 
51 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值