package kuanDuYouXian;
import java.util.Scanner;
class note{
int x;
int y;
int f;
int s;
public note() {
}
}
/**
* @author Administrator
* 宽度优先搜索,用队列来解
*/
public class kuanDuYouXian {
public static void main(String[] args) {
note[] que=new note[2501];
for(int i=0;i<que.length;i++){
que[i]=new note();
}
int[][] a=new int[51][51];
char[][] book=new char[51][51];
char[][] modelArray=null;
int[][] dir={{0,1},{1,0},{0,-1},{-1,0}};
int head,tail,startx,starty,flag,tx,ty,p,q;
p=3;q=2;
Scanner scanner=new Scanner(System.in);
int line= Integer.parseInt(scanner.nextLine());
// int cross= Integer.parseInt(scanner.nextLine());
modelArray=new char[line][line];
for(int i=0;i<line;i++){
char[] lineArray=scanner.nextLine().toCharArray();
for(int j=0;j<lineArray.length;j+=2){
int id=j/2;
char tem=lineArray[j];
modelArray[i][id]=tem;
}
}
//初始化
head=1;
tail=1;
startx=0;
starty=0;
que[tail].x=startx;
que[tail].y=starty;
que[tail].s=0;
tail++;
book[startx][starty]='1';
flag=0;
while(head<tail){
for(int i=0;i<dir.length;i++){
tx=que[head].x+dir[i][0];
ty=que[head].y+dir[i][1];
//判断是否越界
if(tx>=0&&ty>=0&&tx<line&&ty<line){
if(modelArray[tx][ty]=='0'&&book[tx][ty]!='1'){
book[tx][ty]='1';
//插入新的点到队列中
que[tail].x=tx;
que[tail].y=ty;
que[tail].s=que[head].s+1;
tail++;
}
}
if(tx==p&&ty==q){
flag=1;
break;
}
}
if(flag==1){
break;
}
head++;
}
System.out.println(que[tail-1].s);
}
}
广度优先搜索(队列实现)
最新推荐文章于 2023-10-17 13:56:29 发布