Description
Both Saya and Kudo like balloons. One day, they heard that in the central park, there will be thousands of people fly balloons to pattern a big image.
They were very interested about this event, and also curious about the image.
Since there are too many balloons, it is very hard for them to compute anything they need. Can you help them?
You can assume that the image is an N*N matrix, while each element can be either balloons or blank.
Suppose element A and element B are both balloons. They are connected if:
i) They are adjacent;
ii) There is a list of element C1, C2, … , Cn, while A and C1 are connected, C1 and C2 are connected …Cn and B are connected.
And a connected block means that every pair of elements in the block is connected, while any element in the block is not connected with any element out of the block.
To Saya, element A (Xa,Ya) and B (Xb,Yb) is adjacent if |Xa-Xb|+|Ya-Yb|≤1
But to Kudo, element A (Xa,Ya) and element B (Xb,Yb) is adjacent if |Xa-Xb|≤1 and |Ya-Yb|≤1
They want to know that there’s how many connected blocks with there own definition of adjacent?
Input
The input consists of several test cases.
The first line of input in each test case contains one integer N (0 Each of the next N lines contains a string whose length is N, represents the elements of the matrix. The string only consists of 0 and 1, while 0 represents a block and 1represents balloons.
The last case is followed by a line containing one zero.
Output
For each case, print the case number (1, 2 …) and the connected block’s numbers with Saya and Kudo’s definition. Your output format should imitate the sample output. Print a blank line after each test case.
Sample Input
5
11001
00100
11111
11010
10010
0
Sample Output
Case 1: 3 2
题意
1代表气球,0代表空白,现在有两位小朋友要数相连的气球块一共有多少块
Saya数四个方向的气球,Kudo数八个方向的
Solution
搜!
AC代码
#include<iostream>
#include<cstdio>
using namespace std;
int n;
char c[101][101];
bool a[101][101];
bool b[101][101];
int q1[8]={1,1,1,0,0,-1,-1,-1},e1[8]={1,0,-1,1,-1,0,1,-1}; //Kudo
int q2[4]={0,0,1,-1},e2[4]={1,-1,0,0}; //Saya
void dfs1(int x,int y,int sum)
{
if(x<0||x>=n||y<0||y>=n) return;
if(b[x][y]==0) return; //如果到达越界&&没有可以搜的气球了,返回
for(int i=0;i<8;++i)
{
b[x][y]=0;
int xx=x+q1[i];
int yy=y+e1[i];
dfs1(xx,yy,sum);
}
}
void dfs2(int x,int y,int sum)
{
if(x<0||x>=n||y<0||y>=n) return;
if(a[x][y]==0) return;
for(int i=0;i<4;++i)
{
a[x][y]=0;
int xx=x+q2[i];
int yy=y+e2[i];
dfs2(xx,yy,sum);
}
}
int main()
{
int nu=0;
while(scanf("%d",&n)!=EOF&&n!=0)
{
++nu;
int sum1=0,sum2=0;
for(int i=0;i<n;++i)
{
getchar();
scanf("%s",&c[i]);
}
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
{
if(c[i][j]=='1')
{
b[i][j]=1;
a[i][j]=1;
}
if(c[i][j]=='0')
{
b[i][j]=0;
a[i][j]=0;
}
} //没有空格,只能这么做了- -
}
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
if(b[i][j]) dfs1(i,j,++sum1);
}
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
if(a[i][j]) dfs2(i,j,++sum2);
}
printf("Case %d: %d %d\n",nu,sum2,sum1);
printf("\n");
}
return 0;
}