Skip to content

Commit 8164bd6

Browse files
authored
Update Shortest Path in Binary Matrix.java
1 parent 859072d commit 8164bd6

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed
Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,37 @@
11
class Solution {
2+
private final int[][] DIRS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {1, -1}, {-1, -1}};
3+
24
public int shortestPathBinaryMatrix(int[][] grid) {
3-
int n = grid.length;
4-
if (n == 0 || grid[0][0] == 1 || grid[n - 1][n - 1] == 1) {
5+
if (grid[0][0] == 1) {
56
return -1;
67
}
8+
int numRows = grid.length;
9+
int numCols = grid[0].length;
10+
boolean[][] visited = new boolean[numRows][numCols];
711
Queue<int[]> queue = new LinkedList<>();
8-
int numberOfSteps = 0;
9-
boolean[][] visited = new boolean[n][n];
10-
queue.add(new int[] {0, 0});
12+
queue.add(new int[]{0, 0});
1113
visited[0][0] = true;
14+
int numOfSteps = 0;
1215
while (!queue.isEmpty()) {
16+
numOfSteps++;
1317
int size = queue.size();
1418
while (size-- > 0) {
1519
int[] removed = queue.remove();
16-
if (removed[0] == n - 1 && removed[1] == n - 1) {
17-
return numberOfSteps + 1;
20+
int x = removed[0];
21+
int y = removed[1];
22+
if (x == numRows - 1 && y == numCols - 1) {
23+
return numOfSteps;
1824
}
19-
for (int[] dir : EIGHT_DIRS) {
20-
int newX = removed[0] + dir[0];
21-
int newY = removed[1] + dir[1];
22-
if (newX >= 0
23-
&& newX < n
24-
&& newY >= 0
25-
&& newY < n
26-
&& !visited[newX][newY]
27-
&& grid[newX][newY] == 0) {
28-
queue.add(new int[] {newX, newY});
25+
for (int[] dir : DIRS) {
26+
int newX = x + dir[0];
27+
int newY = y + dir[1];
28+
if (newX >= 0 && newY >= 0 && newX < numRows && newY < numCols && !visited[newX][newY] && grid[newX][newY] == 0) {
29+
queue.add(new int[]{newX, newY});
2930
visited[newX][newY] = true;
3031
}
3132
}
3233
}
33-
numberOfSteps++;
3434
}
3535
return -1;
3636
}
37-
38-
private static final int[][] EIGHT_DIRS = {
39-
{0,1},{0,-1},{1,0},{-1,0},{1,-1},{-1,1},{-1,-1},{1,1}};
4037
}

0 commit comments

Comments
 (0)