因为不用求路径长度,只用求次数
挺巧妙的是每次搜索一次就把搜索过的位置变成*,就可以知道哪些联通哪些不是了
#include <iostream>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn = 105;
char map[ maxn ][ maxn ];
int dirx[ 8 ] = {1, -1, 0, 0, 1, -1, 1, -1};
int diry[ 8 ] = {0, 0, 1, -1, 1, -1, -1, 1};
int m, n;
int sum;
struct Node {
int x, y;
} cur, nex;
bool path ( int x, int y ) {
if ( x >= 0 && x < m && y >= 0 && y < n && map[ x ][ y ] == '@' )
return true;
return false;
}
void bfs ( int x, int y ) {
cur.x = x, cur.y = y;
map[ x ][ y ] = '*';
queue<Node> q;
q.push ( cur );
while ( !q.empty () ) {
cur = q.front ();
q.pop ();
for ( int i = 0; i < 8; ++i ) {
nex.x = cur.x + dirx[ i ];
nex.y = cur.y + diry[ i ];
if ( path ( nex.x, nex.y ) ) {
//联通的就置成*
map[ nex.x ][ nex.y ] = '*';
q.push ( nex );
}
}
}
}
int main () {
while ( cin >> m >> n ) {
if ( m == 0 && n == 0 )
break;
sum = 0;
for ( int i = 0; i < m; ++i )
cin >> map[ i ];
for ( int i = 0; i < m; ++i )
for ( int j = 0; j < n; ++j )
if ( map[ i ][ j ] == '@' ) { //找到每一个@,找到次数就+1
sum++;
bfs ( i, j );
}
cout << sum << endl;
}
return 0;
}