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
| class Solution { private int[][] directions = new int[][] { { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 } };
public int shortestPathBinaryMatrix(int[][] grid) { if (grid[0][0] == 1) { return -1; } if (grid.length == 1) { return 1; } int n = grid.length; boolean[][] visited = new boolean[n][n]; Deque<int[]> q = new ArrayDeque<>(); q.offer(new int[] { 0, 0 }); visited[0][0] = true; int steps = 1; while (!q.isEmpty()) { for (int i = q.size(); i > 0; i--) { int[] currPos = q.poll(); for (int[] direction : directions) { int newRow = currPos[0] + direction[0]; int newCol = currPos[1] + direction[1]; if (!isOutOfBound(n, newRow, newCol) && grid[newRow][newCol] == 0 && !visited[newRow][newCol]) { if (newRow == n - 1 && newCol == n - 1) { return steps + 1; } q.offer(new int[] { newRow, newCol }); visited[newRow][newCol] = true; } } } steps += 1; } return -1; }
private boolean isOutOfBound(int n, int row, int col) { return row < 0 || row >= n || col < 0 || col >= n; } }
|