[[1,1,0,1],
[1,0,1,0],
[1,1,1,1],
[1,0,1,1]]
题目描述:1 表示可以经过某个位置,求解从 (0, 0) 位置到 (tr, tc) 位置的最短路径长度。
采用bfs方法:
import java.util.*;
public class ShortestPath {
public static void main(String[] args){
/*
grids: 测试用例
*/
int[][] grids = {
{1,1,0,1},
{1,0,1,0},
{1,1,1,1},
{1,0,1,1}
};
int tr = 2;//target row
int tc = 3;//target column
int length = shortestPath(grids,tr,tc);//最短路径长度
System.out.println(length);
}
/**
* @param grids
* @param tr : target row
* @param tc : target column
* @return : shorest path length
*/
public static int shortestPath(int[][] grids,int tr,int tc){
if(grids[0][0]==0 || grids[tr][tc]==0) return -1;
int[][] directions = {
{1,0},{-1,0},{0,1},{0,-1}
};
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0,0});//(0,0)位置
grids[0][0] = 0;//标记
int num = 0;
while(!queue.isEmpty()){
num++;
int size = queue.size();
for(int i = 0;i<size;i++){
int[] prev = queue.poll();
if(tr==prev[0] && tc==prev[1]) return num-1;
int prev_x = prev[0];
int prev_y = prev[1];
for(int[] direction:directions){
int newx = prev_x + direction[0];
int newy = prev_y + direction[1];
if(newx>=0 && newx<grids.length && newy>=0 && newy<grids[0].length){
queue.offer(new int[]{newx,newy});
grids[prev_x][prev_y] = 0;//标记
}
}
}
}
return -1;
}
}