[LeetCode] 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_i
andC_{i+1}
are connected 8-directionally (ie., they are different and share an edge or corner) C_1
is at location(0, 0)
(ie. has valuegrid[0][0]
)C_k
is at location(N-1, N-1)
(ie. has valuegrid[N-1][N-1]
)- If
C_i
is 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.
Example 1:
Input: [[0,1],[1,0]] Output: 2
Example 2:
Input: [[0,0,0],[1,1,0],[1,1,0]] Output: 4
Note:
1 <= grid.length == grid[0].length <= 100
grid[r][c]
is0
or1
二进制矩阵中的最短路径。
在一个 N × N 的方形网格中,每个单元格有两种状态:空(0)或者阻塞(1)。
一条从左上角到右下角、长度为 k 的畅通路径,由满足下述条件的单元格 C_1, C_2, ..., C_k 组成:
相邻单元格 C_i 和 C_{i+1} 在八个方向之一上连通(此时,C_i 和 C_{i+1} 不同且共享边或角)
C_1 位于 (0, 0)(即,值为 grid[0][0])
C_k 位于 (N-1, N-1)(即,值为 grid[N-1][N-1])
如果 C_i 位于 (r, c),则 grid[r][c] 为空(即,grid[r][c] == 0)
返回这条从左上角到右下角的最短畅通路径的长度。如果不存在这样的路径,返回 -1 。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-path-in-binary-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
跟大部分的 flood fill 的题型类似,这是一道给一个起点然后问你是否能到达终点的题目。这道题的起点和终点分别是matrix的左上角和右下角,无非是这道题的traverse的规则是可以往八个方向走,一般的题是只能往四个方向走。其他部分就是正常BFS题目的翻版,如果不理解可以先做其他flood fill的题。
时间O(mn)
空间O(mn) - visited matrix
Java实现
1 class Solution { 2 int[][] dirs = new int[][] { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { -1, 1 }, { -1, -1 }, { 1, 1 }, { 1, -1 } }; 3 4 public int shortestPathBinaryMatrix(int[][] grid) { 5 int m = grid.length; 6 int n = grid[0].length; 7 // corner case 8 if (grid[0][0] == 1 || grid[m - 1][n - 1] == 1) { 9 return -1; 10 } 11 // normal case 12 int count = 0; 13 boolean[][] visited = new boolean[m][n]; 14 visited[0][0] = true; 15 Queue<int[]> queue = new LinkedList<>(); 16 queue.offer(new int[] { 0, 0 }); 17 while (!queue.isEmpty()) { 18 int size = queue.size(); 19 for (int i = 0; i < size; i++) { 20 int[] cur = queue.poll(); 21 if (cur[0] == m - 1 && cur[1] == n - 1) { 22 return count + 1; 23 } 24 for (int k = 0; k < 8; k++) { 25 int nextX = cur[0] + dirs[k][0]; 26 int nextY = cur[1] + dirs[k][1]; 27 if (nextX < 0 || nextX >= m || nextY < 0 || nextY >= n || visited[nextX][nextY] == true 28 || grid[nextX][nextY] == 1) { 29 continue; 30 } 31 queue.offer(new int[] { nextX, nextY }); 32 visited[nextX][nextY] = true; 33 } 34 } 35 count++; 36 } 37 return -1; 38 } 39 }
标签:Binary,Matrix,int,queue,grid,Path,nextX,nextY,cur 来源: https://www.cnblogs.com/cnoodle/p/14401484.html