黑白圖(八連塊)

Problem 46: 八連塊


Time Limit:1 Ms| Memory Limit:128 MB
Difficulty:1

Description

輸入一個n*n(n最大爲30)的黑白圖像(1表示黑色,0表示白色),任務是統計其中八連塊的個數。如果兩個黑格子有公共邊或者有公共頂點,就說它們屬於同一個八連塊。
如下圖所示,八連塊的個數爲3。
100100
001010
000000
110000
111000
010100

Input

第一行輸入一個n 表示圖的大小
接下來n行 用來表示圖的組成

Output

輸出八連塊的個數

Sample Input

6
100100
001010
000000
110000
111000
010100

Sample Output

3




代碼



#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAXSIZE 35
int count = 0;
int mat[MAXSIZE][MAXSIZE];													
int visit[MAXSIZE][MAXSIZE];                                                //標記數組                                                                                                                                                                                  
int b[8][2] = {-1, 0, -1, 1, 0, 1, 1, 1, 1, 0, 1, -1, 0, -1, -1, -1};		//八個方向

void dfs(int x, int y);

int main()
{
	int i, j;
	int n;
	char s[MAXSIZE];
	scanf("%d", &n);
	memset(mat, 0, sizeof(mat));						//初始化爲0
	memset(visit, 0, sizeof(visit));
	for(i = 0; i < n; i++)
	{
		scanf("%s", s);
		for(j = 0; j < n; j++)							//四周圍上一圈0的牆
			mat[i + 1][j + 1] = s[j] - '0';
	}
//	int count = 0;
	for(i = 1 ; i <= n; i++)
	{
		for(j = 1; j <= n; j++)
		{
			if(!visit[i][j] && mat[i][j])					//沒有被標記並且是黑色格
			{
				count++;
				dfs(i, j);				
			}
		}
	}
	printf("%d\n", count);
	return 0;
}

void dfs(int x, int y)
{
	int i;
	if(visit[x][y] || !mat[x][y])
		return;
	visit[x][y] = 1;
	for(i = 0; i< 8; i++)
	{
		x = x + b[i][0];
		y = y + b[i][1];
		dfs(x, y);
		x -= b[i][0];				//x, y重新變回到原來的位置
		y -= b[i][1];
	}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章