POJ 1562

题意:给一幅图,找出其中有多少个连同子图(8个方向都算相连)

 

思路: BFS

 

#include <iostream> #include <string> #define F(i,a,b) for (int i=a;i<=b;i++) using namespace std; int h, w, Q[10000][2], move[8][2] = { {0,1}, {1, 0}, {-1, 0}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1} }; char map[102][102]; bool mk[102][102]; void bfs(int x, int y) { memset(Q, 0, sizeof(Q) ); int now = 1, last = 1; Q[1][0] = x, Q[1][1] = y; while (now <=last ) { mk[ Q[now][0] ][ Q[now][1] ] = true; int nowx = Q[now][0], nowy = Q[now][1] ; F(i,0,7) { int newx = nowx + move[i][0], newy = nowy+move[i][1]; if (0<=newx && newx <h && 0<=newy && newy<w && !mk[newx][newy] && map[newx][newy]=='@') { last++; Q[last][ 0 ] = newx, Q[last][1] = newy; } } now++; } } int main() { int total; while ( scanf("%d%d", &h, &w) && !(!h && !w) ) { total = 0; F(i,0,h-1) scanf("%s", map[i] ); memset(mk, 0, sizeof(mk) ); F(i,0,h-1) { F(j,0,w-1) if (!mk[i][j] && map[i][j] == '@') { bfs(i,j); total++; } } printf("%d/n", total); } return 0; }

你可能感兴趣的:(POJ 1562)