hdu 1241 AC广搜

点击打开链接,原地址
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][n];
		 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;
		}
		

	 	
	 
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值