Problem Type : Graph(BFS)
#include<cstdio>
#include<cstring>
#include<queue>
#define max 200
using namespace std;
int color[max][max],count=0,n;
char mat[max][max];
int X[8] ={-1,-1,-1,0,0,1,1,1};
int Y[8] ={-1,0,1,-1,1,-1,0,1};
void bfs(int x,int y)
{
int ux,uy,vx,vy,i,j;
queue<int>Q;
Q.push(x);
Q.push(y);
color[x][y]=1;
while(!Q.empty())
{
ux = Q.front();
Q.pop();
uy = Q.front();
Q.pop();
for(i=0; i<8; i++)
{
vx=ux+X[i];
vy=uy+Y[i];
if((vx>=0 && vx<n) && (uy>=0 &&uy<n) && mat[vx][vy]=='1')
{
if(color[vx][vy]==0)
{
color[vx][vy]=1;
Q.push(vx);
Q.push(vy);
}
}
}
}
}
int main()
{
int i,j,k,l,x=0;
while(scanf("%d",&n)==1)
{
x++;
memset(color,0,sizeof(color));
memset(mat,'\0',sizeof(mat));
getchar();
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
scanf(" %c",&mat[i][j]);
}
}
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
if(color[i][j]==0 && mat[i][j]=='1')
{
bfs(i,j);
count++;
}
}
}
printf("Image number %d contains %d war eagles.\n",x,count);
count =0;
}
}
#include<cstdio>
#include<cstring>
#include<queue>
#define max 200
using namespace std;
int color[max][max],count=0,n;
char mat[max][max];
int X[8] ={-1,-1,-1,0,0,1,1,1};
int Y[8] ={-1,0,1,-1,1,-1,0,1};
void bfs(int x,int y)
{
int ux,uy,vx,vy,i,j;
queue<int>Q;
Q.push(x);
Q.push(y);
color[x][y]=1;
while(!Q.empty())
{
ux = Q.front();
Q.pop();
uy = Q.front();
Q.pop();
for(i=0; i<8; i++)
{
vx=ux+X[i];
vy=uy+Y[i];
if((vx>=0 && vx<n) && (uy>=0 &&uy<n) && mat[vx][vy]=='1')
{
if(color[vx][vy]==0)
{
color[vx][vy]=1;
Q.push(vx);
Q.push(vy);
}
}
}
}
}
int main()
{
int i,j,k,l,x=0;
while(scanf("%d",&n)==1)
{
x++;
memset(color,0,sizeof(color));
memset(mat,'\0',sizeof(mat));
getchar();
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
scanf(" %c",&mat[i][j]);
}
}
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
if(color[i][j]==0 && mat[i][j]=='1')
{
bfs(i,j);
count++;
}
}
}
printf("Image number %d contains %d war eagles.\n",x,count);
count =0;
}
}
No comments:
Post a Comment