题目地址:
http://acm.hdu.edu.cn/showproblem.php?pid=1241
经典深度优先遍历!
#include <stdio.h> #define MAXN 110 #define MAXM 110 int n, m; char field[MAXN][MAXM]; void dfs(int i, int j) { int dx, dy; int nx, ny; field[i][j] = '*'; for( dx = -1; dx <= 1; dx++ ) for( dy = -1; dy <= 1; dy++ ) { nx = i + dx; ny = j + dy; if( nx>=0 && nx<m && ny>=0 && ny<n && field[nx][ny]=='@' ) dfs(nx,ny); } } void solve() { int i, j, res = 0; for( i = 0; i < m; i++ ) for( j = 0; j < n; j++ ) if( field[i][j] == '@' ) { dfs(i,j); res++; } printf("%d ", res); } int main() { int i, j; while( (scanf( "%d%d", &m, &n ) != EOF) && m ) { //printf( "%d %d ", m ,n ); getchar(); for( i = 0; i < m; i++ ) { for( j = 0; j < n; j++ ) scanf("%c",&field[i][j]); getchar(); } /*for( i = 0; i < m; i++ ) { for( j = 0; j < n; j++ ) printf( "%c", field[i][j] ); printf(" "); }*/ solve(); } return 0; }