poor_OIer @ 2024-10-06 20:59:50
P2802 回家
#include<bits/stdc++.h>
using namespace std;
int n,m,a[10][10],flag[10][10];
int endx,endy;
int dx[4]={-1,0,1,0};
int dy[4]={0,1,0,-1};
struct node{
int x,y;
int blood;
int t;
};
queue<node> q;
bool checkpos(int c,int d)
{
if(c<1||c>n||d<1||d>m)
return 0;
return 1;
}
bool checkblood(int c,int d)
{
if(q.front().blood>1)
return 1;
else
{
if(a[c][d]==4)
return 1;
return 0;
}
}
void bfs()
{
while(!q.empty())
{
for(int i=0;i<4;i++)
{
int nx=q.front().x+dx[i];
int ny=q.front().y+dy[i];
if(checkpos(nx,ny)&&!flag[nx][ny]&&checkblood(nx,ny))
{
flag[nx][ny]=1;
node b;
b.x=nx;
b.y=ny;
if(a[nx][ny]!=4)
b.blood=q.front().blood-1;
else
b.blood=6;
b.t=q.front().t+1;
q.push(b);
if(nx==endx&&ny==endy)
{
cout<<q.front().t+1;
return;
}
}
}
q.pop();
}
cout<<-1;
return;
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
cin>>a[i][j];
if(a[i][j]==0)
flag[i][j]=1;
if(a[i][j]==2)
{
flag[i][j]=1;
node b;
b.x=i;
b.y=j;
b.blood=6;
q.push(b);
}
if(a[i][j]==3)
endx=i,endy=j;
}
bfs();
return 0;
}