Skip to content

Commit cca3654

Browse files
authored
Merge pull request #2471 from leahjia/1091-shortest-path-in-binary-matrix
Create: 1091-shortest-path-in-binary-matrix.java
2 parents fe98604 + 7ef34a8 commit cca3654

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Diff for: java/1091-shortest-path-in-binary-matrix.java

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public int shortestPathBinaryMatrix(int[][] grid) {
3+
int n = grid.length;
4+
Queue<Integer[]> q = new LinkedList<>();
5+
q.add(new Integer[]{0, 0, 1}); // row, col, length
6+
7+
boolean[][] visited = new boolean[n][n];
8+
visited[0][0] = true;
9+
10+
int[][] direct = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};
11+
12+
while (!q.isEmpty()) {
13+
Integer[] curr = q.poll();
14+
int r = curr[0];
15+
int c = curr[1];
16+
int length = curr[2];
17+
18+
// out of bounds or no way further
19+
if (Math.min(r, c) < 0 || Math.max(r, c) == n || grid[r][c] == 1) continue;
20+
21+
if (r == n - 1 && c == n - 1) return length;
22+
23+
for (int[] d : direct) {
24+
int newRow = r + d[0];
25+
int newCol = c + d[1];
26+
if (Math.min(newRow, newCol) >= 0 && Math.max(newRow, newCol) < n && !visited[newRow][newCol]) {
27+
q.add(new Integer[]{newRow, newCol, 1 + length});
28+
visited[newRow][newCol] = true;
29+
}
30+
}
31+
}
32+
return -1;
33+
}
34+
35+
}

0 commit comments

Comments
 (0)