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.
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; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】