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
如下图所示,八连块的个数为3。
100100
001010
000000
110000
111000
010100
Input
第一行输入一个n 表示图的大小
接下来n行 用来表示图的组成
接下来n行 用来表示图的组成
Output
输出八连块的个数
Sample Input
6
100100
001010
000000
110000
111000
010100
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];
}
}