bfs模板题,求最短路径。第一层放入起点位置,往下遍历
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int n,m,len,res;
static int startx,starty,endx,endy;
static int map[][],flag[][];
static int dir[][] = {
{0,1},{1,0},{-1,0},{0,-1}
};
static class Node{
int x;
int y;
public Node(int x,int y){
this.x =x;
this.y =y;
}
}
static Queue<Node> q = new LinkedList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
map = new int[n][m];
flag = new int[n][m];
for(int i =0;i<n;i++){
for(int j=0;j<m;j++){
map[i][j] = sc.nextInt();
}
}
startx = sc.nextInt()-1;//因为数组下标从0开始
starty = sc.nextInt()-1;
endx = sc.nextInt()-1;
endy = sc.nextInt()-1;
//1为路,其他为障碍
Node temp = new Node(startx,starty);
q.add(temp);
len = q.size();
bfs();
if (flag[endx][endy] == 0) { // 没有到达终点
System.out.println(-1);
} else { // 到达终点
System.out.println(res);
}
}
private static void bfs() {
while(q.size()!=0){
Node now = q.poll();
if(now.x == endx && now.y == endy){
return;
}
for(int i =0;i<4;i++){
int dx = now.x + dir[i][0];
int dy = now.y + dir[i][1];
if(pd(dx,dy)){
flag[dx][dy] = 1;
Node last = new Node(dx,dy);
q.add(last);
}
}
len--;
if(len == 0){
res ++;
len = q.size();
}
}
}
private static boolean pd(int dx, int dy) {
if(dx<0 || dx>=n||dy<0||dy>=m){
return false;
}
if(map[dx][dy] != 1 || flag[dx][dy] !=0){
return false;
}
return true;
}
}