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
题意:相邻的@为第一个区域,求有多少个区域。
1.此题有八个方位
2.标记要在递归之前,细心
AC代码
# include<iostream>
# include<cstring>
using namespace std;
char a[105][105];
int n,m,ans;
int x[]={0,0,1,-1,1,-1,1,-1};
int y[]={1,-1,0,0,-1,1,1,-1};
void dfs(int i,int j)
{
if (i>n||j>m) return ;
for (int k=0;k<8;k++)
for (int f=0;f<8;f++)
{
if (a[i+x[k]][j+y[f]]=='@')
{
a[i+x[k]][j+y[f]]='*'; 标记要在递归前
dfs(i+x[k],j+y[f]);
}
}
return ;
}
int main ()
{
freopen ("in.txt","r",stdin);
while (cin>>n>>m&&n||m)
{
ans=0;
memset(a,'*',sizeof(a));
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
cin >> a[i][j];
}
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
{
if (a[i][j]=='@')
{
ans++;
dfs(i,j);
}
}
cout << ans << endl;
}
}