Knight Shortest Path
来源:互联网 发布:淘宝添加到桌面没有了 编辑:程序博客网 时间:2024/05/01 10:11
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 destination position, return the length of the route.
Return -1 if knight can not reached.
/** * Definition for a point. * public class Point { * publoc int x, y; * public Point() { x = 0; y = 0; } * public Point(int a, int b) { x = a; y = b; } * } */public class Solution { /** * @param grid a chessboard included 0 (false) and 1 (true) * @param source, destination a point * @return the shortest path */ public int shortestPath(boolean[][] grid, Point source, Point destination) { if (grid == null || grid.length == 0 || grid[0].length == 0) { return -1; } int n = grid.length; int m = grid[0].length; int[] directionX = {1, 1, -1, -1, 2, 2, -2, -2}; int[] directionY = {2, -2, 2, -2, 1, -1, 1, -1}; Queue<Point> queue = new LinkedList<>(); queue.offer(source); int step = 0; while (!queue.isEmpty()) { int size = queue.size(); step++; for (int i = 0; i < size; i++) { Point point = queue.poll(); for (int j = 0; j < 8; j++) { Point adj = new Point( point.x + directionX[j], point.y + directionY[j] ); if (inBound(adj.x, adj.y, grid)) { if (adj.x == destination.x && adj.y == destination.y) { return step; } //走过的点不能再走了,抹掉 grid[adj.x][adj.y] = true; queue.offer(adj); } } } } return -1; } private boolean inBound(int x, int y, boolean[][] grid) { int n = grid.length; int m = grid[0].length; return x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == false; }}
0 0
- Knight Shortest Path
- Knight Shortest Path
- Red Knight's Shortest Path
- Shortest Path
- Shortest Path
- Shortest Path
- hdoj 3631 Shortest Path
- hdu 3631 Shortest Path
- HDU3631 Shortest Path
- hdoj 3631 Shortest Path
- hdu 3631 Shortest Path
- hdu 3631 Shortest Path
- Hdu 3631 Shortest Path
- HDU3631:Shortest Path(Floyd)
- Shortest Path Faster Algorithm
- Dijkstra Shortest Path
- HDU 3631 Shortest Path
- HDU Shortest path
- 在2017年,如何将你的小米4刷上Windows 10 mobile?(后附大量图赏)
- Android动画
- Ubuntu下进行JDK的配置
- BIOS密码破解
- 实现自定义SeekBar
- Knight Shortest Path
- Timer启动一个定时任务
- [notes] JSON notes
- Linux下安装 Nginx + uwsgi + web.py + MySQLdb
- C++模板与标准模板库(STL库)介绍
- Java异常个人小结
- 使用Android Studio进行单元测试
- 极小极大值方法以及alpha-Beta剪枝
- C# 图解教程 类与继承