题目链接
bfs题目,不需多说。
下面是AC代码
import java.util.*;
import java.math.*;
public class Main {
public static int[] dx={1,-1,0,0},dy={0,0,-1,1};
public static int x1,x2,y1,y2;
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
char[][] map=new char[n][n];
sc.nextLine();
for(int i=0;i<n;i++){
String s=sc.nextLine();
map[i]=s.toCharArray();
}
x1=sc.nextInt();
y1=sc.nextInt();
x2=sc.nextInt();
y2=sc.nextInt();
System.out.println(bfs(map));
}
public static int bfs(char[][] map){
int n=map.length;
Queue<int[]> q=new LinkedList<int[]>();
q.offer(new int[]{x1-1,y1-1});
map[x1-1][y1-1]='2';
int step=0;
while(!q.isEmpty()){
int len=q.size();
for(int i=0;i<len;i++){
int[] cur=q.poll();
int x=cur[0];
int y=cur[1];
if(x==x2-1&&y==y2-1){
return step;
}
for(int j=0;j<4;j++){
int xx=x+dx[j];
int yy=y+dy[j];
if(xx<0||yy<0||xx==n||yy==n||map[xx][yy]!='0')
continue;
map[xx][yy]='2';
q.offer(new int[]{xx,yy});
}
}
step++;
}
return -1;
}
}