UVa 352 - The Seasonal War ( DFS求连通块 )
思路
基础DFS
和油田那题思路一毛一样
AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char s[30][30];
int n;
void dfs( int x, int y ){
s[x][y] = '0';
for( int dx = -1; dx <= 1; dx++ ){
for( int dy = -1; dy <= 1; dy++ ){
int nx = x + dx, ny = y + dy;
if( nx >= 0 && nx < n && ny >= 0 && ny < n && s[nx][ny] == '1' )
dfs(nx, ny);
}
}
return;
}
int solve(){
int num = 0;
for( int i = 0; i < n; i++ )
for( int j = 0; j < n; j++ )
if( s[i][j] == '1' ){
dfs(i,j);
num++;
}
return num;
}
int main()
{
int eg, num = 0;
while( ~scanf("%d",&n) ){
memset(s,0,sizeof(s));
for( int i = 0; i < n; i++ )
scanf("%s",s[i]);
eg = solve();
printf("Image number %d contains %d war eagles.\n",++num, eg);
}
return 0;
}