黑白图像 -- 刘汝佳白书P107

输入一个n*n的黑白图像(1表示黑色,0表示白色),任务是统计其中八连块的个数。如果两个黑格子有公共边或者公共顶点,就说它们属于同一个八连块。

(题意是让求连在一起的块有几个,图见书本)

SamInput

6
100100
001010
000000
110000
111000
010100

#include <iostream>
#define MAXN 30
using namespace std;

int mat[MAXN][MAXN], vis[MAXN][MAXN];

void dfs(int x, int y)
{
	if(!mat[x][y] || vis[x][y])
		return;
	
	vis[x][y] = 1; //标记(x,y) 
	
	dfs(x-1, y-1);  dfs(x-1, y);  dfs(x-1, y+1);
	dfs(x, y-1);                  dfs(x, y+1);
	dfs(x+1, y-1);  dfs(x+1, y);  dfs(x+1, y+1);	
}

int main()
{
	//freopen("E:\\input.txt","r",stdin);
	memset(mat, 0, sizeof(mat));
	memset(vis, 0, sizeof(vis));
	char s[MAXN];
	int n;
	cin >> n;
	for(int i=0; i<n; i++)
	{
		cin >> s;
		for(int j=0; j<n; j++)
			mat[i+1][j+1] = s[j] - '0';
	}
	
	int count = 0;
	for(int i=1; i<=n; i++)
		for(int j=1; j<=n; j++)
			if(mat[i][j] && !vis[i][j]){
				count++;
				dfs(i,j);
			}
	
	cout << count << endl;
	return 0;
}


SampleOutput:

3



你可能感兴趣的:(任务)