Problem Type : Graph (BFS)
#include<cstdio>
#include<cstring>
#include<queue>
#define MAX 60
using namespace std;
int n,m,color[MAX][MAX],getgold=0,cou=0;
int X[4]= {-1,0,0,1};
int Y[4]= {0,-1,1,0};
char mat[MAX][MAX];
int bfs(int i,int j)
{
if(mat[i-1][j]=='T')
{
return getgold;
}
else if(mat[i][j-1]=='T')
{
return getgold;
}
else if(mat[i][j+1]=='T')
{
return getgold;
}
else if(mat[i+1][j]=='T')
{
return getgold;
}
queue<int>Q;
Q.push(i);
Q.push(j);
color[i][j]=1;
int vx,vy,k,ux,uy;
while(!Q.empty())
{
ux=Q.front();
Q.pop();
uy=Q.front();
Q.pop();
for(k=0; k<4; k++)
{
vx=ux+X[k];
vy=uy+Y[k];
if(vx>=1 && vx<=n && vy>=1 && vy<=m && mat[vx][vy]!='#')
{
if(color[vx][vy]==0)
{
color[vx][vy]=1;
if(mat[vx][vy]=='G')
{
getgold++;
}
if(mat[vx-1][vy]=='T')
{
continue;
}
else if(mat[vx][vy-1]=='T')
{
continue;
}
else if(mat[vx][vy+1]=='T')
{
continue;
}
else if(mat[vx+1][vy]=='T')
{
continue;
}
Q.push(vx);
Q.push(vy);
}
}
}
}
return getgold;
}
int main()
{
int i,j,len,posi,posj;
while(scanf("%d %d",&m,&n)==2)
{
getgold=0;
getchar();
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
scanf(" %c",&mat[i][j]);
if(mat[i][j]=='P')
{
posi=i;
posj=j;
}
}
}
int k;
cou=0;
k= bfs(posi,posj);
printf("%d\n",k);
memset(color,0,sizeof(color));
memset(mat,'\0',sizeof(mat));
}
return 0;
}
#include<cstdio>
#include<cstring>
#include<queue>
#define MAX 60
using namespace std;
int n,m,color[MAX][MAX],getgold=0,cou=0;
int X[4]= {-1,0,0,1};
int Y[4]= {0,-1,1,0};
char mat[MAX][MAX];
int bfs(int i,int j)
{
if(mat[i-1][j]=='T')
{
return getgold;
}
else if(mat[i][j-1]=='T')
{
return getgold;
}
else if(mat[i][j+1]=='T')
{
return getgold;
}
else if(mat[i+1][j]=='T')
{
return getgold;
}
queue<int>Q;
Q.push(i);
Q.push(j);
color[i][j]=1;
int vx,vy,k,ux,uy;
while(!Q.empty())
{
ux=Q.front();
Q.pop();
uy=Q.front();
Q.pop();
for(k=0; k<4; k++)
{
vx=ux+X[k];
vy=uy+Y[k];
if(vx>=1 && vx<=n && vy>=1 && vy<=m && mat[vx][vy]!='#')
{
if(color[vx][vy]==0)
{
color[vx][vy]=1;
if(mat[vx][vy]=='G')
{
getgold++;
}
if(mat[vx-1][vy]=='T')
{
continue;
}
else if(mat[vx][vy-1]=='T')
{
continue;
}
else if(mat[vx][vy+1]=='T')
{
continue;
}
else if(mat[vx+1][vy]=='T')
{
continue;
}
Q.push(vx);
Q.push(vy);
}
}
}
}
return getgold;
}
int main()
{
int i,j,len,posi,posj;
while(scanf("%d %d",&m,&n)==2)
{
getgold=0;
getchar();
for(i=1; i<=n; i++)
{
for(j=1; j<=m; j++)
{
scanf(" %c",&mat[i][j]);
if(mat[i][j]=='P')
{
posi=i;
posj=j;
}
}
}
int k;
cou=0;
k= bfs(posi,posj);
printf("%d\n",k);
memset(color,0,sizeof(color));
memset(mat,'\0',sizeof(mat));
}
return 0;
}
No comments:
Post a Comment