Skip to content

Commit c5b89c7

Browse files
authored
Create Solution.java
1 parent b548873 commit c5b89c7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
public int shortestPathBinaryMatrix(int[][] grid) {
3+
int n = grid.length;
4+
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) {
5+
return -1;
6+
}
7+
Queue<int[]> queue = new ArrayDeque<>();
8+
boolean[][] vis = new boolean[n][n];
9+
queue.offer(new int[]{0, 0});
10+
vis[0][0] = true;
11+
int[][] dirs = new int[][]{{0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}};
12+
int res = 1;
13+
while (!queue.isEmpty()) {
14+
int size = queue.size();
15+
while (size-- != 0) {
16+
int[] cur = queue.poll();
17+
if (cur[0] == n - 1 && cur[1] == n - 1) {
18+
return res;
19+
}
20+
for (int[] dir : dirs) {
21+
int x = cur[0] + dir[0], y = cur[1] + dir[1];
22+
if (x >= 0 && x < n && y >= 0 && y < n && !vis[x][y] && grid[x][y] == 0) {
23+
vis[x][y] = true;
24+
queue.offer(new int[]{x, y});
25+
}
26+
}
27+
}
28+
++res;
29+
}
30+
return -1;
31+
}
32+
}

0 commit comments

Comments
 (0)