图:黑白图像问题。

it2025-12-05  31

输入一个n*n的黑白图像,(1表示黑色,0表示白色),统计其中相连块的个数。

例如:

100100

001010

000000

110000

111000

010100

上面矩阵所示图形中有3块黑色图像。

解答: 用递归求解。从每个未被访问过的黑格子除法, 递归访问所有相连的八个黑格子。

#define SIZE 6 int mat[SIZE][SIZE], vis[SIZE][SIZE]; void dfs( int x, int y) { if (( x < 0 ) || ( y < 0 ) || ( x >= SIZE ) || ( y >= SIZE )) return; if (( !mat[x][y] )||( vis[x][y])) return; vis[x][y] = 1; dfs(x+1,y); dfs(x-1,y); dfs(x,y+1); dfs(x,y-1); dfs(x+1,y+1); dfs(x-1,y+1); dfs(x+1,y-1); dfs(x-1,y-1); } int main () { char grid[SIZE*SIZE + 1]; while(scanf("%s", grid) == 1) { memset(mat, 0, sizeof(mat)); memset(vis, 0, sizeof(vis)); for ( int i = 0; i < SIZE; i++ ) for ( int j = 0; j < SIZE; j++ ) mat[i][j] = ( grid[i*SIZE + j] == '0' ) ? 0 : 1; int count = 0; for ( int i = 0; i < SIZE; i++ ) for ( int j = 0; j < SIZE; j++ ) if ( !vis[i][j] && mat[i][j] ) { count++; dfs(i,j); } printf("%d\n", count); } return 0; }

 

转载于:https://www.cnblogs.com/tsubasa/archive/2012/12/05/2804034.html

相关资源:数据结构—成绩单生成器
最新回复(0)