您的位置:首页 > 其它

hdu 1241 AC广搜

2015-08-10 17:20 281 查看
点击打开链接,原地址
package cn.hncu.search;

import java.util.Scanner;

public class searchbfs {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int count=0;
while(sc.hasNext()){
int m=sc.nextInt();
int n=sc.nextInt();
Plot plots[][]=new Plot[m]
;
for(int i=0;i<m;i++){
String str =sc.next();
for(int j=0;j<n;j++){
plots[i][j]=new Plot(i,j);
plots[i][j].c=str.charAt(j);//以上都是接受字符串,以及收数字
}
}

for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(plots[i][j].c=='@'&&!plots[i][j].flag){//开始进行判断,是否满足条件以及是否访问过
PlotQueue queue=new PlotQueue();
queue.add(plots[i][j]);//满足条件,进队列
bfs(plots,queue);//开始广搜
count++;//搜索完成后就直接加一个
}
}
}
System.out.println(count);
}
}

private static void bfs(Plot[][] plots, PlotQueue queue) {
while(!queue.isEmpty()){//判断是否为空,
Plot plot=queue.pop();//位于一个的出队列
int px,py;
int m=plots.length;//为后面的要求 y值
int n=plots[0].length;//x 的最大值
for(int i=0;i<8;i++){
px=plot.x+a[i][0];
py=plot.y+a[i][1];
if(px>=0&&px<m && py>=0&&py<n &&plots[px][py].c=='@' &&! plots[px][py].flag){
plots[px][py].flag=true;//访问过之后就改变标签
queue.add(plots[px][py]);//满足条件就直接加
}

}

}

}
final static int a[][]={//该点的四周的八个点必须一一开始遍历
{0,-1},
{0,1},
{-1,0},
{1,0},
{-1,-1},
{-1,1},
{1,-1},
{1,1}
};

}

//点的作用,
class Plot{
int x,y;
char c;
boolean flag=false;
public Plot(int x, int y) {
this.x = x;
this.y = y;
}

}

//广搜必须要到队列,就像深搜用到地 递归一样
class PlotQueue{

Plot plot[];
public PlotQueue(){
plot=new Plot[100];

}

final int FRONT=0;
int end=0;
public void add(Plot p) {//进站
plot[end++]=p;
}
public Plot pop() {//出栈,第一个先出去,其余的往前移动
if(end<=0){
return null;
}
Plot p=plot[FRONT];
if(end>1){
for(int i=0;i<end;i++){
plot[i]=plot[i+1];
}

}end--;

return p;
}
public boolean isEmpty() {//判断是都为空
if(end<=0){
return true;
}

return false;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  广搜