-
Notifications
You must be signed in to change notification settings - Fork 863
Expand file tree
/
Copy pathTheMaze.java
More file actions
53 lines (46 loc) · 1.86 KB
/
Copy pathTheMaze.java
File metadata and controls
53 lines (46 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Time Complexity : O(mn)
// Space Complexity : O(mn)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
// Your code here along with comments explaining your approach
/*
We do a dfs recursive approach to roll the ball from the start position until destination coordinates are met.
As mentioned in the problem, the ball can be rolled in 4 directions, so we declare a dirs array and iterate the
i,j coordinates in all 4 directions. We need to roll ball until a wall is hit, so we use a while loop to iterate
with the given direction until conditions go out of bounds.Now, we decrement to the previous position and explore
in all directions from that position and we also keep track of visited array to mark positions such that we
dont visit them again.
*/
class Solution {
boolean flag;
int[][] dirs;
int m, n;
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
this.flag = false;
this.dirs = new int[][] {{-1, 0} , {0, -1} , {1, 0} , {0, 1}};
this.m = maze.length;
this.n = maze[0].length;
boolean[][] visited = new boolean[m][n];
dfs(maze, start[0] , start[1], destination, visited);
return flag;
}
private void dfs(int[][] maze, int i , int j, int[] destination, boolean[][] visited) {
if(i == destination[0] && j == destination[1]) {
flag = true;
return;
}
visited[i][j] = true;
for(int[] dir : dirs) {
int nr = dir[0] + i;
int nc = dir[1] + j;
while(nr >= 0 && nc >= 0 && nr < m && nc < n && maze[nr][nc] == 0) {
nr += dir[0];
nc += dir[1];
}
nr -= dir[0];
nc -= dir[1];
if(!visited[nr][nc])
dfs(maze, nr, nc , destination, visited);
}
}
}