package leetcode.search;
import javafx.util.Pair;
import java.util.LinkedList;
import java.util.Queue;
public class MinPathLength {
int solution(int[][] grids,int tr,int tc){
final int[][] direction= {{1,0},{-1,0},{0,1},{0,-1}};
int maxRow = grids.length;
int maxColumn = grids[0].length;
Queue<Pair<Integer,Integer>> queue = new LinkedList<>() ;
queue.add(new Pair<>(0,0));
int pathLength = 0;
while (!queue.isEmpty()){
int size = queue.size();
pathLength++;//确定了下一步在+1
while (size-->0){//先找到确定没问题的一步,因为肯定是多种混合的道路
Pair<Integer,Integer> p = queue.poll();
int key = p.getKey();
int value = p.getValue();
grids[key][value] = 0;//标记为已经走过
for (int[] i : direction){
int nr = key + i[0];
int cr =value+ i[1];
if (nr<0||cr<0||nr>=maxRow||cr>=maxColumn||grids[nr][cr]==0){
continue;//越界
}
if (nr ==tr&&cr==tc){
return pathLength;
}
queue.add(new Pair<>(nr,cr));
}
}
}
return -1;
}
public static void main(String[] args) {
new MinPathLength().solution(new int[][]{{1,1,0,1}, {1,0,1,0}, {1,1,1,1}, {1,0,1,1}},3,3);
}
}
size-->0 先判断size>0 再减1,相反的是--size,先减再判断
两个while循环,确定下一步的走法,理解还不是很深刻
int[][] direction 对4个方向的设计
Pair常用的键值对的存储数据结构
Queue可以new LinkedList, PriorityQueue等等