Problem Type : BFS(Harder)
#include<stdio.h>
#include<string.h>
#include<queue>
#define MAX 1003
using namespace std;
int X[]= {0,0,1,-1};
int Y[]= {1,-1,0,0};
int node,edge ,ux,uy,vx,vy;
char mat[MAX][MAX];
queue<int>fire,joy;
bool broke,cross;
bool boundary()
{
if(vx>=0 && vx<node && vy>=0 && vy<edge)
return true;
else
return false;
}
void bfsf()
{
int num = fire.size();
int i;
num/=2;
if(num==0)
{
return;
}
while(num--)
{
ux = fire.front();
fire.pop();
uy = fire.front();
fire.pop();
for(i=0; i<4; i++)
{
vx=ux+X[i];
vy=uy+Y[i];
if(boundary()&& mat[vx][vy]=='.')
{
mat[vx][vy]='F';
fire.push(vx);
fire.push(vy);
}
}
}
}
void bfsj()
{
int num = joy.size();
int i;
num/=2;
if(num==0)
{
broke = false;
return;
}
while(num--)
{
ux = joy.front();
joy.pop();
uy = joy.front();
joy.pop();
for(i=0;i<4;i++)
{
vx= ux+X[i];
vy= uy +Y[i];
if(!boundary())
{
cross = false ;
return;
}
if(boundary()&& mat[vx][vy]=='.')
{
mat[vx][vy]='J';
joy.push(vx);
joy.push(vy);
}
}
}
}
int main()
{
int test,i,j,k;
scanf("%d",&test);
while(test--)
{
scanf("%d %d",&node,&edge);
getchar();
while(!fire.empty())
{
fire.pop();
}
while(!joy.empty())
{
joy.pop();
}
for(i=0; i<node; i++)
{
for(j=0; j<edge; j++)
{
scanf(" %c",&mat[i][j]);
if(mat[i][j]=='F')
{
fire.push(i);
fire.push(j);
}
else if(mat[i][j]=='J')
{
joy.push(i);
joy.push(j);
}
}
}
int cou =0;
cross = true;
broke = true;
while(true)
{
cou++;
bfsf();
bfsj();
if(broke == false|| cross== false)
{
break;
}
}
if(broke == false)
{
printf("IMPOSSIBLE\n");
}
else if(cross == false)
{
printf("%d\n",cou);
}
}
}
No comments:
Post a Comment