-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution490.java
More file actions
54 lines (46 loc) · 1.77 KB
/
Solution490.java
File metadata and controls
54 lines (46 loc) · 1.77 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
54
import java.util.LinkedList;
import java.util.Queue;
public class Solution490 {
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
int m = maze.length;
int n = maze[0].length;
Queue<int[]> queue = new LinkedList<int[]>();
queue.offer(start);
boolean[][] visited = new boolean[m][n];
visited[start[0]][start[1]] = true;
int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
while (!queue.isEmpty()) {
int[] curr = queue.poll();
int row = curr[0];
int col = curr[1];
if (row == destination[0] && col == destination[1]) {
return true;
}
for (int[] dir : dirs) {
while (row >= 0 && row < m && col >= 0 && col < n && maze[row][col] == 0) {
row += dir[0];
col += dir[1];
}
row -= dir[0];
col -= dir[1];
if (visited[row][col] == true) {
continue;
}
visited[row][col] = true;
if (row == destination[0] && col == destination[1]) {
return true;
}
queue.offer(new int[]{row, col});
}
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] maze = new int[][]{{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}};
int[] start = new int[]{0, 4};
int[] destination = new int[]{4, 4};
Solution490 s = new Solution490();
System.out.println(s.hasPath(maze, start, destination));
}
}