• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }

 

posted @ 2017-03-14 03:31  neverlandly  阅读(1436)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3