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:

 package fbOnsite;

 import java.util.*;

 public class KnightShortestPath {
public static int shortestPath(int[][] board, int[] src, int[] dst) {
int[][] directions = new int[][]{{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
int m = board.length;
int n = board[0].length;
int res = 0; Queue<Integer> queue = new LinkedList<Integer>();
HashSet<Integer> visited = new HashSet<Integer>();
queue.offer(src[0]*n + src[1]);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i=0; i<size; i++) {
int cur = queue.poll();
visited.add(cur);
int x = cur / n;
int y = cur % n;
if (x == dst[0] && y == dst[1]) return res; for (int[] dir : directions) {
int nx = x + dir[0];
int ny = y + dir[1];
if (nx<0 || nx>=m || ny<0 || ny>=n || visited.contains(nx*n+ny) || board[nx][ny]!=0)
continue;
queue.offer(nx*n + ny);
}
}
res++;
}
return res;
} /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] board = new int[][] {{0,1,0},{0,0,0},{0,0,0}};
int[] src = new int[]{2,0};
int[] dst = new int[]{2,2};
int res = shortestPath(board, src, dst);
System.out.println(res);
} }

Lintcode: Knight Shortest Path的更多相关文章

  1. hdu-----(2807)The Shortest Path(矩阵+Floyd)

    The Shortest Path Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  2. zoj 2760 How Many Shortest Path 最大流

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1760 Given a weighted directed graph ...

  3. The Shortest Path in Nya Graph

    Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...

  4. hdu 3631 Shortest Path(Floyd)

    题目链接:pid=3631" style="font-size:18px">http://acm.hdu.edu.cn/showproblem.php?pid=36 ...

  5. Shortest Path(思维,dfs)

    Shortest Path  Accepts: 40  Submissions: 610  Time Limit: 4000/2000 MS (Java/Others)  Memory Limit: ...

  6. Shortest Path

    Shortest Path Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)T ...

  7. (中等) HDU 4725 The Shortest Path in Nya Graph,Dijkstra+加点。

    Description This is a very easy problem, your task is just calculate el camino mas corto en un grafi ...

  8. 【ZOJ2760】How Many Shortest Path

    How Many Shortest Path 标签: 网络流 描述 Given a weighted directed graph, we define the shortest path as th ...

  9. [Swift]LeetCode847. 访问所有节点的最短路径 | Shortest Path Visiting All Nodes

    An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph. graph.lengt ...

随机推荐

  1. ABP使用Miniprofiler监测EF

    在上篇教程中,我们在WebApi项目中集成了Miniprofiler,本篇文章中,将继续集成Miniprofiler EF6,以实时监测分析EF的执行语句.执行效率等.Miniprofiler会针对E ...

  2. 01.pandas

    01.Series # -*- coding: utf-8 -*- """ Series 객체 특징 - pandas 제공 1차원 자료구성 - DataFrame 칼 ...

  3. pycharm中join的应用

    学习python这几天发现jion的两种用法 li = "alexericrain" v = ["_".join(li)] print (v) #第一种输出结果 ...

  4. fastadmin模态框(弹出框)

    用法: 在html页面新建一个按钮用来触发事件 <a href="javascript:;" class="btn btn-success btn-add &quo ...

  5. 使用BITSADMIN下载文件

    BITSADMIN /RAWRETURN /TRANSFER D /PRIORITY HIGH http://127.0.0.1:80/file.exe C:\ProgramData\file.exe

  6. Mybatis 通用 Mapper 和 Spring 集成

    依赖 正常情况下,在原有依赖基础上增加的 mapper-spring. <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spr ...

  7. Hibernate 映射多对多关联关系

    映射多对多,需要建立一张中间表 一共三张表,一个是 Category,一个是 Item,还有一个是 Categories_Items Categories_Items 作为中间表,其包含两个列,分别对 ...

  8. Hibernate 映射一对一关联关系

    基于外键的方式: 附上代码: public class Manager { private Integer mgrId; private String mgrName; private Departm ...

  9. CSS入门介绍(二)CSS选择器

    css选择器 什么是选择器? 选择器是你构造好网页的结构,需要给这些结构赋予样式,这时候就需要用到选择器,利用选择器将元素与样式一一对应:两者的对应关系可以是一对一,一对多,多对一. 选择器的分类: ...

  10. 输入、输出与Mad Libs 游戏。

    name1=input('请输入一个名字:') name2=input('再输入一个名字:') time1=input('请输入一段时间:') print('{},是傻子,{},{}吃不了鸡'.for ...