问题 X: Oil Deposit
时间限制: 1 Sec 内存限制: 32 MB
题目描述
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.
输入
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.
输出
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.
样例输入
3 4
**@*
*@*@
@***
4 5
@**@@
*@**@
@**@*
@**@@
0 3
样例输出
1 2
解题思路
- 两个二维数组,一个存储输入,一个作为标记。
- 用递归的方法,读取某个点的上下左右8个方位的坐标,判断是否符合条件递归进入下一层。
ps
本题遍历八个方向的方法值得学习。
int dx[]={-1,-1,-1,0,0,1,1,1},
dy[]={-1,0,1,-1,1,-1,0,1};
for(int i=0;i<=7;i++)
search(x+dx[i],y+dy[i],id);
方法1(借鉴)
#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
char map[101][101];
int m=0,n=0,ans;
int mark[101][101]={0},
dx[]={-1,-1,-1,0,0,1,1,1},
dy[]={-1,0,1,-1,1,-1,0,1};
void search(int x,int y,int id)
{
if(x<0||x>=m||y<0||y>=n)
return ;
if(mark[x][y]>0||map[x][y]!='@')
return ;
mark[x][y]=id;
for(int i=0;i<=7;i++)
search(x+dx[i],y+dy[i],id);
}
int main()
{
while(scanf("%d%d",&m,&n)&&m!=0)
{
ans=0;//清零
memset(mark,0,sizeof(mark));
for(int i=0;i<m;i++)
scanf("%s",map[i]);//注意其中没有空格,需用字符串输入
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if((mark[i][j]==0)&&(map[i][j]=='@'))//没有被访问过
search(i,j,++ans);
}
cout<<ans<<endl;
n=0;
}
}
方法2
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int m, n, cnt;
char vis[110][110];
int mark[110][110],
dx[]={-1,-1,-1,0,0,1,1,1},
dy[]={-1,0,1,-1,1,-1,0,1};
void dfs(int l, int r, int cnt){
if(l<1||l>m||r<1||r>n||mark[l][r]>0||vis[l][r]!='@')
return;
mark[l][r]=cnt;
for(int i=0; i<8; i++){
dfs(l+dx[i], r+dy[i], cnt);
}
}
int main(){
while(cin>>m>>n&&m!=0){
memset(mark, 0, sizeof(mark));
cnt=0;
char ch;
for(int i=1; i<=m; i++){
for(int j=1; j<=n; j++){
cin>>ch;
vis[i][j]=ch;
}
}
for(int i=1; i<=m; i++){
for(int j=1; j<=n; j++){
if(mark[i][j]==0 && vis[i][j]=='@')
dfs(i, j, ++cnt);
}
}
cout<<cnt<<endl;
}
return 0;
}