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 first line of input in each test case contains one integer N (0<N≤100), which represents the size of the matrix.
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
Sample Input
5 11001 00100 11111 11010 10010 0
Sample Output
Case 1: 3 2
解题思路:
将输入内容转化为数字数组,循环时,遇到值为1的数字,统计值+1,然后对其所在的板块进行清除(即将与其相临的1变为0,但两人对相邻的定义不同),
细节处理:
因为要设计两个清除函数,所以将各个变量定义为全局变量更为方便,因为输入的数字(0和1)是连续的所以先用字符串进行存放,然后再分解。清除函数为递归函数。
代码:
#include<iostream>
#include<string>
using namespace std;
int n;
char a[102][102];
char b[102][102];
int ax[4]={0,0,1,-1};
int ay[4]={-1,1,0,0};
int bx[8]={0,0,1,-1,-1,-1,1,1};
int by[8]={-1,1,0,0,-1,1,-1,1};
void dfsa(int x,int y)
{
if(x<1||x>n||y<1||y>n) return;
if(a[x][y]=='0') return;
a[x][y]='0';
for(int i=0;i<4;i++)
{int a=x+ax[i];int b=y+ay[i];
dfsa(a,b);}
}
void dfsb(int x,int y)
{
if(x<1||x>n||y<1||y>n) return;
if(b[x][y]=='0') return;
b[x][y]='0';
for(int i=0;i<8;i++)
{int a=x+bx[i];int b=y+by[i];
dfsb(a,b);}
}
int main()
{
int i,j;
int num=0;
while(cin>>n&&n)
{
string s;
int count1=0,count2=0;
for(i=1;i<=n;i++)
{
cin>>s;
for(j=0;j<s.length();j++)
{
a[i][j+1]=s[j]; b[i][j+1]=s[j];
}
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(a[i][j]=='1')
{
dfsa(i,j);
count1++;
}
if(b[i][j]=='1')
{
dfsb(i,j);
count2++;
}
}
cout<<"Case "<<++num<<": "<<count1<<" "<<count2<<endl;
cout<<endl;
}
return 0;
}