HDOJ1241 Oil Deposits

该博客介绍了如何运用BFS(宽度优先搜索)算法解决HDOJ1241题目的油田连通性问题。通过判断不同@字符的连通状态,确定油田的数量。博主分享了一段Java实现的代码示例。
摘要由CSDN通过智能技术生成


题意:每一个@的九宫格有其他@字符,说明这几个@字符是连通的,每一块不连通的@字符集是一块油田,问有几块?

本题利用BFS广搜,废话不多说,上代码(java):

package cn.hncu.search;

import java.util.Scanner;

public class SearchBFS {

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		while(sc.hasNext()){
			int n=sc.nextInt();
			int m=sc.nextInt();
			if(n==0&&m==0)
				return;
			Plot[][] plots=new Plot[n][m];
			for (int i = 0; i < n; i++) {
				String str=sc.next();
				for (int j = 0; j < m; j++) {
					plots[i][j]=new Plot(i, j, str.charAt(j));
				}
			}
			PlotQueue plotQueue=new PlotQueue();
			//广搜要队列
			int count=0;
			for (int i = 0; i < plots.length; i++) {
				for (int j = 0; j < plots[i].length; j++) {
					if(plots[i][j].c=='@'&&!plots[i][j].isVisit){
						plots[i][j].isVisit=true;
						//符合要求加入队列
						plotQueue.add(plots[i][j]);
						//开始广搜
						bfs(plotQueue,plots);
						count++;
					}
				}
			}
			System.out.println(count);
		}

	}

	static int[][] dir={{-1,-1},{0,-1},{1,-1},
			             {-1,0},        {1,0},
			             {-1,1}, {0,1},  {1,1}};
	private static void bfs(PlotQueue plotQueue, Plot[][] plots) {
		//队列非空
		while(!plotQueue.isEmpty()){
			//取出操作数
			Plot plot=plotQueue.pop();
			//遍历周围
			for (int k = 0; k < dir.length; k++) {
				int i=plot.x+dir[k][0];
				int j=plot.y+dir[k][1];
				if(i>=0&&i<plots.length && j>=0&&j<plots[i].length
						&& plots[i][j].c=='@' && !plots[i][j].isVisit){
					//符合加入队列
					plots[i][j].isVisit=true;
					plotQueue.add(plots[i][j]);
				}
			}
		}
		
	}

}
class Plot{
	int x,y;
	char c;
	boolean isVisit;
	public Plot(int x, int y, char c) {
		this.x = x;
		this.y = y;
		this.c = c;
	}
	Plot child;
}
class PlotQueue{
	Plot first;//头结点
	Plot end;//尾节点
	public void add(Plot p){
		if(first==null){//队列为空时
			//头尾皆指第一个
			end=p;
			first=p;
		}
		else{
			end.child=p;//将新加入的加入队列,
			end=p;//使尾指针更新
		}
	}
	
	public Plot pop(){
		if(first!=null){//头指针不为空及 队列不空
			Plot p=first;//确定排除的节点
			first=first.child;//更新头指针
			return p;
		}
		return null;
	}
	public boolean isEmpty(){
		if(first==null)//头指针为空及 队列空
			return true;
		return false;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值