【BFS】LeetCode 1091. 二进制矩阵中的最短路径
题目链接
思路
BFS 找最短路模板题
代码
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
if(grid[0][0] == 1 || grid[grid.length - 1][grid[0].length - 1] == 1){
return -1;
}
Queue<Pair<Pair<Integer, Integer>, Integer>> queue = new LinkedList<>();
boolean[][] visited = new boolean[grid.length][grid[0].length];
queue.offer(new Pair<>(new Pair<>(0, 0), 1));
int[] dx = new int[]{1, 0, -1, 0, 1, 1, -1, -1};
int[] dy = new int[]{0, 1, 0, -1, 1, -1, 1, -1};
while(!queue.isEmpty()){
Pair<Pair<Integer, Integer>, Integer> currentState = queue.remove();
int currentStep = currentState.getValue();
Pair<Integer, Integer> currentPos = currentState.getKey();
if(currentPos.getKey() == grid.length - 1 && currentPos.getValue() == grid[0].length - 1){
return currentStep;
}
for(int i = 0; i < 8; i++){
int nextX = currentPos.getKey() + dx[i];
int nextY = currentPos.getValue() + dy[i];
if(valid(nextX, nextY, visited, grid)){
queue.offer(new Pair<>(new Pair<>(nextX, nextY), currentStep + 1));
visited[nextX][nextY] = true;
}
}
}
return -1;
}
private boolean valid(int nextX, int nextY, boolean[][] visited, int[][] grid) {
return (
0 <= nextX && nextX < grid.length && 0 <= nextY && nextY < grid[0].length &&
!visited[nextX][nextY] && grid[nextX][nextY] == 0
);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能