-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1091_Shortest_Path_in_Binary_Matrix.java
More file actions
51 lines (47 loc) · 1.45 KB
/
1091_Shortest_Path_in_Binary_Matrix.java
File metadata and controls
51 lines (47 loc) · 1.45 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
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
if (grid[0][0] == 1 || grid[grid.length - 1][grid.length - 1] == 1) {
return -1;
}
int[][] dir = { { -1, -1 }, { 0, -1 }, { 1, -1 }, { -1, 0 }, { 1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 } };
Queue<Point> queue = new LinkedList<>();
queue.offer(new Point(0, 0));
int shortest = 1;
int parent = 1;
int child = 0;
while (!queue.isEmpty()) {
Point p = queue.poll();
if (p.x == grid.length - 1 && p.y == grid.length - 1) {
return shortest;
}
parent--;
grid[p.x][p.y] = 1;
for (int i = 0; i < 8; i++) {
int deltaX = p.x + dir[i][0];
int deltaY = p.y + dir[i][1];
if (deltaX < 0 || deltaX == grid.length || deltaY < 0 || deltaY == grid.length) {
continue;
}
if (grid[deltaX][deltaY] == 1) {
continue;
}
queue.offer(new Point(deltaX, deltaY));
child++;
}
if (parent == 0) {
parent = child;
child = 0;
shortest++;
}
}
return -1;
}
class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}