Oil Deposits
Oil Deposits |
The GeoSurvComp geologic survey company is responsible for detectingunderground oil deposits. GeoSurvComp works with one large rectangularregion of land at a time, and createsa grid that divides the land into numerous square plots. It then analyzeseach plot separately,using sensing equipment to determine whether or not the plot contains oil.
A plot containingoil is called a pocket. If two pockets are adjacent, then they are part ofthe same oil deposit. Oildeposits can be quite large and may contain numerous pockets. Your job is todetermine how many different oil deposits are contained in a grid.
Input
The input file contains one or more grids. Each grid begins with a linecontaining m and n, thenumber of rows and columns in the grid, separated by a single space. Ifm = 0 it signals the endof the input; otherwise and
.Followingthis are m lines of n characterseach (not counting the end-of-line characters). Each character corresponds toone plot, and iseither `*', representing the absence of oil, or `@', representing an oil pocket.
Output
For each grid, output the number of distinct oil deposits. Two differentpockets are part of thesame 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
题意分析:
简单的入门级DFS,统计@连着的块数
解题思路:
1. 设置两个二维数组,一个用于存储输入的字符矩阵,一个用于标记对应字符是否被访问过;
2. DFS搜索即可,注意边界条件以及标记。
代码如下:
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
const int MAXSIZE = 100 + 5;
char oil[MAXSIZE][MAXSIZE];
int vis[MAXSIZE][MAXSIZE];
void dfs(int i, int j)
{
if(vis[i][j]||oil[i][j]!='@') return;
vis[i][j]=1;
dfs(i-1,j-1); dfs(i-1,j); dfs(i-1,j+1);
dfs(i,j-1); dfs(i,j+1);
dfs(i+1,j-1); dfs(i+1,j); dfs(i+1,j+1);
}
int main()
{
int m,n;
//freopen("572.txt","r",stdin);
while(cin>>m>>n)
{
if(m==0&&n==0) break;
string str;
memset(oil,1,sizeof(oil));
memset(vis,0,sizeof(vis));
for(int i=0;i<m;i++){
cin>>str;
for(int j=0;j<n;j++) oil[i+1][j+1]=str[j];
}
int count_num=0;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(!vis[i][j]&&oil[i][j]=='@') { count_num++; dfs(i,j);}
}
}
cout<<count_num<<endl;
}
return 0;
}