题意:每一个@的九宫格有其他@字符,说明这几个@字符是连通的,每一块不连通的@字符集是一块油田,问有几块?
本题利用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;
}
}