c语言 搜索题油田问题,HDU1241 经典油田问题(BFS)
先粘個(gè)原題:
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits.
GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides
the land into numerous square plots. 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.
Input
The input file 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. 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). Each character corresponds to one plot, and is either ‘*’, representing the
absence of oil, or ‘@’, representing an oil pocket.
Output
For each grid, output the number of distinct oil deposits. Two different pockets are part of the same
oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain
more than 100 pockets.
Sample Input
1 1
*
3 5
*@*@*
* *@* *
*@*@*
1 8
@@ * * * * @ *
5 5
* * * * @
* @@*@
* @ * * @
@@@*@
@@* * @
0 0
Sample Output
0
1
2
2
題目大致意思是在一塊m * n的范圍內(nèi)用“@”標(biāo)記油田,用“ * ”標(biāo)記不存在油田的位置。假如一個(gè)點(diǎn)被標(biāo)記為油田,那么這個(gè)點(diǎn)的周圍九宮格范圍內(nèi)如果還存在油田,這兩個(gè)油田就是一塊油田,問給出的圖中油田的塊數(shù)。基本思路就是先遍歷,一旦找到一處油田進(jìn)入BFS遞歸,將這個(gè)油田所在的一整塊油田全部標(biāo)記,計(jì)數(shù)器加一。之后遍歷繼續(xù),直至每塊油田均被標(biāo)記,代碼如下。其中注釋部分是從 BJFU 1143小蝌蚪找媽媽那道題的模板挪過來的,不同之處就在于那道題只有上下左右四個(gè)方向,而這道題有八個(gè)方向。
#include
#include
using namespace std;
int a[105][105];
int n,m,ans=0,man=0;
void bfs(int i,int j)
{
if(a[i][j]==1)
{
// man++;
// if(man>ans)
// ans=man;
a[i][j]=0;
if(i-1>0) bfs(i-1,j);
if(j-1>0) bfs(i,j-1);
if(i+1<=n) bfs(i+1,j);
if(j+1<=m) bfs(i,j+1);
if(i-1>0&&j-1>0) bfs(i-1,j-1);
if(i-1>0&&j+1<=m) bfs(i-1,j+1);
if(i+1<=n&&j-1>0) bfs(i+1,j-1);
if(i+1<=m&&j+1<=m) bfs(i+1,j+1);
}
}
int main()
{
//freopen("1.txt","r",stdin);
while(cin>>n>>m&&(m||n))
{
int num = 0;
if(n == 0&&m == 0)return 0;
int i,j;
char w;
ans=0;
memset(a,0,sizeof(a));
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
cin>>w;
if(w=='@')
a[i][j]=1;
} //讀出原圖并標(biāo)記
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
if(a[i][j]==1)
{
num++;
// man=0;
bfs(i,j);
}
}
cout<
}
return 0;
}
總結(jié)
以上是生活随笔為你收集整理的c语言 搜索题油田问题,HDU1241 经典油田问题(BFS)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c语言微信昵称大全女生优雅经典的,微信昵
- 下一篇: c语言中的数字菱形,打印数字菱形,急啊,