Leetcode: The Maze(Unsolved locked problem)
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination. The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes. Example 1 Input 1: a maze represented by a 2D array 0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0 Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4) Output: true
Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.Example 2 Input 1: a maze represented by a 2D array 0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0 Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (3, 2) Output: false
Explanation: There is no way for the ball to stop at the destination.Note:
There is only one ball and one destination in the maze.
Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.
- Search in the four possible directions when coming to a stopping point (i.e. a new starting point).
- Keep track of places that you already started at in case you roll back to that point.
public class Solution {
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
boolean[][] startedHere = new boolean[maze.length][maze[0].length]; // mark visited starting points
return dfs(maze, startedHere, start, destination);
}
private boolean dfs(int[][] maze, boolean[][] startedHere, int[] start, int[] destination) {
if (startedHere[start[0]][start[1]]) return false;
if (Arrays.equals(start, destination)) return true;
startedHere[start[0]][start[1]] = true; // in case we roll back to a point we already started at
BiPredicate<Integer, Integer> roll = (rowInc, colInc) -> {
int row = start[0], col = start[1]; // init new start row and col
while (canRoll(maze, row + rowInc, col + colInc)) {
row += rowInc;
col += colInc;
}
return dfs(maze, startedHere, new int[]{row, col}, destination); // pass in new start to dfs
};
if (roll.test(1, 0)) return true; // roll up
if (roll.test(0, 1)) return true; // roll right
if (roll.test(-1, 0)) return true; // roll down
if (roll.test(0, -1)) return true; // roll left
return false; // return false if no paths led to destination
}
private boolean canRoll(int[][] maze, int row, int col) {
if (row >= maze.length || row < 0 || col >= maze[0].length || col < 0) return false; // stop at borders
return maze[row][col] != 1; // stop at walls (1 -> wall)
}
}
UPDATE: Also including one without using BiPredicate on every recursive call since it runs faster
public class Solution {
private static final int[] DIRECTIONS = { 0, 1, 0, -1, 0 };
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
boolean[][] startedHere = new boolean[maze.length][maze[0].length];
return dfs(maze, startedHere, start, destination);
}
private boolean dfs(int[][] maze, boolean[][] startedHere, int[] start, int[] destination) {
if (startedHere[start[0]][start[1]]) return false;
if (Arrays.equals(start, destination)) return true;
startedHere[start[0]][start[1]] = true;
for (int i = 0; i < DIRECTIONS.length - 1; i++) {
int[] newStart = roll(maze, start[0], start[1], DIRECTIONS[i], DIRECTIONS[i + 1]);
if (dfs(maze, startedHere, newStart, destination)) return true;
}
return false;
}
private int[] roll(int[][] maze, int row, int col, int rowInc, int colInc) {
while (canRoll(maze, row + rowInc, col + colInc)) {
row += rowInc;
col += colInc;
}
return new int[]{row, col};
}
private boolean canRoll(int[][] maze, int row, int col) {
if (row >= maze.length || row < 0 || col >= maze[0].length || col < 0) return false;
return maze[row][col] != 1; // 1 is a wall
}
}
Leetcode: The Maze(Unsolved locked problem)的更多相关文章
- Leetcode: Max Consecutive Ones II(unsolved locked problem)
Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at mos ...
- Leetcode: The Maze III(Unsolved Lock Problem)
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] The Maze III 迷宫之三
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] The Maze II 迷宫之二
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- [LeetCode] The Maze 迷宫
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- Leetcode: The Maze II
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...
- Leetcode 365. Water and Jug Problem
可以想象有一个无限大的水罐,如果我们有两个杯子x和y,那么原来的问题等价于是否可以通过往里面注入或倒出水从而剩下z. z =? m*x + n*y 如果等式成立,那么z%gcd(x,y) == 0. ...
- Leetcode: Find Permutation(Unsolve lock problem)
By now, you are given a secret signature consisting of character 'D' and 'I'. 'D' represents a decre ...
- Leetcode 笔记 117 - Populating Next Right Pointers in Each Node II
题目链接:Populating Next Right Pointers in Each Node II | LeetCode OJ Follow up for problem "Popula ...
随机推荐
- java_ATM_GUI
Test 界面: import java.awt.Menu; import java.io.BufferedReader; import java.io.File; import java.io.Fi ...
- django模板中获取域名地址
获取域名: {{ request.get_host }} 获取路径:{{ request.path }} 获取协议 {{ request.scheme }}
- KaliLinuxNetHunter教程实施刷机解锁Bootloader
KaliLinuxNetHunter教程实施刷机解锁Bootloader 当用户将前面的工作都准备完成后,即可开始刷机.其中,整个刷机过程分为三个步骤,分别是解锁Bootloader.刷入第三方Rec ...
- url传参过程中文字需编码、解码使用
1.链接进行编码跳转:window.location.href = encodeURI(url) 2.获取当前链接进行解码:decodeURI(window.location); 3.获取url中参数 ...
- port bridge enable命令导致的环路
1.故障描述 前几天机房一台连接数据中心与核心交换的交换机宕机(硬件故障),机房有备用的设备,随即更换(配置也是早就配置好了的),但是下午就出现数据中心网络丢包问题,表现为存在mac漂移 2.拓扑 核 ...
- Exception in thread "main" java.lang.UnsupportedClassVersionError: org/apache/maven/cli/MavenCli : Unsupported major.minor version 51.0 报错
此报错经常出现,项目中使用的maven版本为3.2.5版本但是去写自动化脚本又需要去3.5.2版本.经常搞混,需要记录一下: 解决如下: 再次install如下: 验证成功!
- SVN-您的主机中的软件中止了一个已建立的连接
关于这个问题,网络上有各种解决的办法,关闭防火墙,HTTP/HTTPS切换,改端口... ...但我都试了没有用.本来一直用的好好的,突然就出现了这个问题,而且在几分钟前都是正常的.下面来说说我都干了 ...
- mysql学习1
1.什么是数据库? 数据的仓库,如在ATM的示例中创建了一个db目录,称其为数据库 2.安装 下载 http://dev.mysql.com/downloads/mysql/ 安装 windows: ...
- connect socket的超时设置
最近项目中,有个需求是检测某ip地址是否是通的,使用了socket的connect函数.但是,当ip地址写错的话,connect就会一直阻塞在那里,大概2.3分钟才能返回连接失败.这对于用户来说是不可 ...
- __x__(34)0908第五天__ 定位 position
position 定位 指将原始摆放到页面的任意位置. 继承性:no 默认值:static 没有定位,原始出现在正常的文档流中 可选值: static : 默认值,元素没有开启定位 ...
Example 2
Input 1: a maze represented by a 2D array
0 0 1 0 0
Note: