水题,其实是DFS的一个应用,重点是如何将递归转化为非递归 #include <cstdio> using namespace std; const int MAX = 101; typedef struct _Node { int x,y,step; }Node; char data[MAX][MAX]; Node stack[MAX*MAX]; int row,col,stacki; bool getnext( const Node& left , Node& result , int step ) { static const int x[8] = {0,0,1,1,1,-1,-1,-1}; static const int y[8] = {1,-1,1,0,-1,1,0,-1}; result.x = left.x + x[step]; result.y = left.y + y[step]; if( result.x >= 0 && result.x < row && result.y >= 0 && result.y < col && data[result.x][result.y] == 'W') return true; else return false; } void find( Node & mid ) { stacki = 0 ; Node mid2,mid3; mid.step = 0; stack[ stacki++ ] = mid; while( stacki != 0 ) { mid2 = stack[--stacki]; data[ mid2.x ][ mid2.y ] = '.'; for( ; mid2.step < 8 ; mid2.step++ ) if( getnext( mid2 , mid3 , mid2.step ) ) { mid2.step++; stack[stacki++] = mid2; mid3.step = 0 ; stack[stacki++] = mid3; break; } } } int main() { scanf("%d%d",&row,&col); for( int i = 0 ; i != row ; ++i ) scanf("%s",data[i]); int result = 0 ; for( int i = 0 ; i != row ; ++i ) for( int j = 0 ; j != col ; ++j ) if( data[i][j] == 'W') { Node mid ; mid.x = i ; mid.y = j ; find( mid ); ++result; } printf("%d/n",result); return 0; }