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 0Sample Output
0 1 2 2
题意
问有几个不相连的@,八个方向都算
思路
bfs
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>
#include <cstdio>
using namespace std;
struct node
{
int x,y;
};
int dx[] = {0,0,1,-1,1,1,-1,-1};
int dy[] = {1,-1,0,0,-1,1,-1,1};
int main()
{
int n,m,i,j,num;
while(cin>>n>>m&&(n||m)){
char a[120][120];
num=0;
for(i=1;i<=n;i++)
{
getchar();
for(j=1;j<=m;j++)
{
scanf("%c",&a[i][j]);
if(a[i][j]=='*')
num++;
}
}
int ans =0;
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(a[i][j]=='@')
{
ans++;
node u,v;
queue<node> q;
u.x=i,u.y=j;
q.push(u);
while(!q.empty())
{
u=q.front();
q.pop();
for(int k=0;k<8;k++)
{
int tx = u.x+dx[k];
int ty = u.y+dy[k];
if(tx>=1&&ty>=1&&tx<=n&&ty<=m&&a[tx][ty]=='@')
{
v.x=tx;
v.y=ty;
a[tx][ty]='*';
num++;
q.push(v);
}
}
}
}
}
}
cout<<ans<<endl;
}
return 0;
}

本文介绍了一个用于探测矩形土地上油藏分布的算法。通过创建网格并使用传感设备分析每个地块来确定是否存在油藏。算法采用广度优先搜索(BFS)来识别独立的油藏数量,考虑了地块之间的八个方向连接。
998

被折叠的 条评论
为什么被折叠?



