题目链接
思路:BFS
就是一个朴素的BFS就可以出来,定义一个二维数组,每个[i][j]表示到这个位置的最小路径长度
初始化nums二维数组,这个数组就是上面说的用来存到达每个位置的最小的路径长度,nums[0][0]=1,那么后面的就是前面的+1。
代码中都有注释。
代码:
class Solution {
int[][] fx = {
{1,0},
{0,1},
{-1,0},
{0,-1},
{1,-1},
{-1,1},
{1,1},
{-1,-1},
};//八个方向
int[][] nums = null;
int n = 0;
public int shortestPathBinaryMatrix(int[][] grid) {
n = grid.length;
if(grid[0][0]==1 || grid[n-1][n-1]==1){
return -1;
}
if(n==1){
return grid[0][0] == 0 ? 1 : -1;
}
nums = new int[n][n];
//初始化最大的路径长度
for(int i = 0 ; i < n ;i++){
for(int j = 0; j < n;j++){
nums[i][j] = Integer.MAX_VALUE;
}
}
//初始化当前的步长
nums[0][0] = 1;
//广搜的队列
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{0,0});
//进行广搜
bfs(grid, queue);
return nums[n-1][n-1] == Integer.MAX_VALUE ? -1 : nums[n-1][n-1];
}
public void bfs(int[][] grid, Queue<int[]> queue){
Queue<int[]> afterQueue = new LinkedList<>();
//遍历队列
while (!queue.isEmpty()){
int[] curPoint = queue.poll();
if(curPoint[0]==n-1 &&curPoint[1]==n-1){
return;
}
//向八个方向遍历
for(int[] f : fx){
int nextx = curPoint[0] + f[0];
int nexty = curPoint[1] + f[1];
if(nextx < 0 || nextx >=n || nexty < 0 || nexty >=n || grid[nextx][nexty]==1){
continue;
}
if(nums[nextx][nexty] == Integer.MAX_VALUE){
afterQueue.add(new int[]{nextx,nexty});
//更新下一个单元格的最小路径长度
nums[nextx][nexty] = nums[curPoint[0]][curPoint[1]] + 1;
}
}
}
//如果从 前一个队列 没有一个点可以深搜,那么就结束了
if(!afterQueue.isEmpty()){
bfs(grid,afterQueue);
}
}
}
好好学习。
不打扰是我的温柔。