Problem Type : Graph(BFS)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#define max 101
using namespace std;
char mat[max][max];
int m,n,count=0;
int color[max][max],cost[0][0];
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,k;
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(k=0;k<8;k++)
{
vx = ux+X[k];
vy = uy+Y[k];
if((vx>=1&&vx<=m) && (vy>=1&&vy<=n) && mat[vx][vy]=='@')
{
if(!color[vx][vy])
{
color[vx][vy]=1;
Q.push(vx);
Q.push(vy);
}
}
}
}
}
int main()
{
int i,j,k;
while(scanf("%d",&m)&&m)
{
scanf("%d",&n);
memset(color,0,sizeof(color));
memset(cost,0,sizeof(cost));
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
scanf(" %c",&mat[i][j]);
}
}
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
if(!color[i][j] && mat[i][j]=='@')
{
bfs(i,j);
count++;
}
}
}
printf("%d\n",count);
count=0;
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#define max 101
using namespace std;
char mat[max][max];
int m,n,count=0;
int color[max][max],cost[0][0];
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,k;
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(k=0;k<8;k++)
{
vx = ux+X[k];
vy = uy+Y[k];
if((vx>=1&&vx<=m) && (vy>=1&&vy<=n) && mat[vx][vy]=='@')
{
if(!color[vx][vy])
{
color[vx][vy]=1;
Q.push(vx);
Q.push(vy);
}
}
}
}
}
int main()
{
int i,j,k;
while(scanf("%d",&m)&&m)
{
scanf("%d",&n);
memset(color,0,sizeof(color));
memset(cost,0,sizeof(cost));
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
scanf(" %c",&mat[i][j]);
}
}
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
if(!color[i][j] && mat[i][j]=='@')
{
bfs(i,j);
count++;
}
}
}
printf("%d\n",count);
count=0;
}
return 0;
}
No comments:
Post a Comment