3533: 黑白图像

Time Limit(Common/Java):1000MS/3000MS Memory Limit:65536KByte
Total Submit: 760 Accepted:171
Total Submit: 760 Accepted:171
Description
输入一个n*n的黑白图像(1表示黑色,0表示白色),任务是统计其中八连块的个数。如果两个黑格子有公共边或者公共顶点,就说它们属于同一个八连块。如图所示的图形有3个八连块。
Input
第1行输入一个正整数n(n≤700),此后输入n行,每行是由n个0或1组成的字符串。
Output
在输入黑白图像中,八连块的个数
Sample Input
6
100100
001010
000000
110000
111000
010100
Sample Output
3
给你一个黑白图像,确定有几个八连块,因为这个有的话就要一直找下去,所以会叉爆栈的64M空间,要使用广度优先搜索
#include <stdio.h> #include <queue> using namespace std; #define N 1010 char mat[N][N]; void bfs(int x,int y) { mat[x][y] = '0'; queue<pair<int,int> > q; pair<int,int> p; q.push(make_pair(x,y)); while(!q.empty()) { p = q.front(); q.pop(); for(int i = -1 ; i <= 1 ; i++) { for(int j = -1 ; j <= 1 ; j++) { int nx = p.first + i; int ny = p.second + j; if(mat[nx][ny]=='1') { mat[nx][ny]='0'; q.push(make_pair(nx,ny)); } } } } } int main() { int n, x, y, f= 0; scanf("%d", &n); for(x= 0 ; x< n;x++) scanf("%s",mat[x]); for (x = 0; x < n; x++) for (y =0; y < n; y++) if (mat[x][y]=='1') {bfs(x,y);f++;} printf("%d ", f); return 0; }