【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
);
}
}