1091. Shortest Path in Binary Matrix
In an N by N square grid, each cell is either empty (0) or blocked (1).
A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that:
- Adjacent cells
C_iandC_{i+1}are connected 8-directionally (ie., they are different and share an edge or corner) C_1is at location(0, 0)(ie. has valuegrid[0][0])C_kis at location(N-1, N-1)(ie. has valuegrid[N-1][N-1])- If
C_iis located at(r, c), thengrid[r][c]is empty (ie.grid[r][c] == 0).
Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1.
class Solution { public int shortestPathBinaryMatrix(int[][] grid) { int n = grid.length; if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1; boolean[][] visited = new boolean[n][n]; Queue<int[]> q = new LinkedList<>(); q.offer(new int[] { 0, 0 }); visited[0][0] = true; int[][] directions = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { 1, -1 }, { 1, 1 }, { -1, 0 }, { -1, -1 }, { -1, 1 } }; int cost = 1; while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { int[] cur = q.poll(); if (cur[0] == n - 1 && cur[1] == n - 1) return cost; for (int[] dir : directions) { int x = cur[0] + dir[0]; int y = cur[1] + dir[1]; if (x >= 0 && x < n && y >= 0 && y < n && !visited[x][y] && grid[x][y] == 0) { q.offer(new int[] { x, y }); visited[x][y] = true; } } } cost++; } return -1; } }

浙公网安备 33010602011771号