BFS(Breadth First Search)宽度优先搜索
这是一种分层搜索的算法,即从出发点先搜索一遍一步就能到达的点,然后再拿这些找到的点再做一次这样的操作,知道不符合要求,或者所有的结点都扫了为止
模板
#include<cstdio>
#include<queue>
using namespace std;
void bfs(int a);
{
queue<类型> q;//定义一个队列
q.push(a);//可以把队列看成一把枪,push就是把子弹压入枪膛
while(q.size()) //当枪里面还有子弹的话
{
int x=q.front();//扣动扳机
q.pop();//子弹出膛
//可能有for循环,把这一颗子弹转成好多颗子弹再压入枪膛
if(//满足题目中的条件)
q.push(//把符合条件的子弹压入枪膛);
}
}
例题
题目描述
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits.
GeoSurvComp地质调查公司负责探测地下石油矿床。
GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots.
GeoSurvComp一次处理一个大的矩形区域,并创建一个网格,将土地划分为许多正方形地块。
It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil.
然后,它分别分析每个图,使用传感设备来确定图中是否含有石油。
A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit.
一块含有石油的地皮叫做口袋。如果两个凹陷相邻,则它们是同一个油藏的一部分。
Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.
石油储量可能相当大,并可能包含许多口袋。你的工作是确定一个网格中有多少不同的石油储量。
输入描述
The input contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space.
输入包含一个或多个网格。每个网格以包含m和n的行开始,m和n是网格中的行数和列数,由一个空格分隔。
If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters).
如果m=0,则表示输入结束;否则,1<=m<=100,1<=n<=100。接下来是m行,每行n个字符(不包括行尾字符)。
Each character corresponds to one plot, and is either *', representing the absence of oil, or
@’, representing an oil pocket.
每个字符对应一个图,或者是表示没有油的“#”,或者是表示油袋的“@”。
输出描述
are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
水平、垂直或对角相邻。一个储油罐的容量不能超过100个。
输入样例
1 1
3 5
#@#@#
##@##
#@#@#
1 8
@@####@#
5 5
####@
#@@#@
#@##@
@@@#@
@@##@
0 0
输出样例
0
1
2
2
代码
#include<stdio.h>
#include<queue>
#include<string.h>
using namespace std;
int m,n;
struct node
{
int x;
int y;
};
char s[110][110];
int a[8][2]={-1,-1,-1,0,-1,1,0,-1,0,1,1,-1,1,0,1,1,};
int bfs(int i,int j)
{
queue<node> q;
node temp;
temp.x=i;
temp.y=j;
q.push(temp);
s[i][j]='#';
while(q.size())
{
temp=q.front();
q.pop();
s[temp.x][temp.y]='#';
for(int k=0;k<=7;k++)
{
if(s[temp.x+a[k][0]][temp.y+a[k][1]]=='@')
{
node temp1;
temp1.x=temp.x+a[k][0];
temp1.y=temp.y+a[k][1];
q.push(temp1);
}
}
}
}
int main()
{
while(1)
{
int cnt=0;
scanf("%d %d",&m,&n);
if(m==0)
break;
for(int i=0;i<m;i++)
scanf("%s",s[i]);
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(s[i][j]=='@')
{
bfs(i,j);
cnt++;
}
}
printf("%d\n",cnt);
}
}