- 这题刚开始写的时候,人走迷宫的时候,没有用
visit
数组,导致 t 了。 - 然后没有注意到题目中的
portions
,意思是火苗可能有多个起点,人只能有一个起点。
最后分析一下bfs 和 dfs 的时间复杂度:
-
邻接矩阵 MxN (每个点最多访问一次,如果每个点有多种状态,就再乘以状态数)
-
领接表 (v+e) (每个点最多访问一次)
当然 以上的结论建立在有 visit 数组的前提上,否则时间复杂度可能大大提升。
奈何我的英语理解实在不过关,所以wa了很多次,最后才过了。
代码如下:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
#define inf 0x3f3f3f3f
int maze[1005][1005];
int vis[1005][1005];
int n,m;
int flag;
struct node
{
int x;
int y;
int p;
};
int re;
int dir[4][2] = { { 0,1},{1,0},{0,-1},{-1,0}};
queue<node> quf;
void bfs1()
{
node tmp;
while(!quf.empty())
{
node f = quf.front();
quf.pop();
for(int i=0;i<4;i++)
{
tmp.x = f.x+dir[i][0];
tmp.y = f.y + dir[i][1];
if(tmp.x<0||tmp.x>=n||tmp.y<0||tmp.y>=m||maze[tmp.x][tmp.y]==-1)continue;
if(maze[tmp.x][tmp.y]<= maze[f.x][f.y]+1)continue;
maze[tmp.x][tmp.y] = maze[f.x][f.y]+1;
quf.push(tmp);
}
}
}
void bfs2(node st)
{
queue<node> qu;
st.p = 1;
qu.push(st);
vis[st.x][st.y]=1;
node tmp;
while(!qu.empty())
{
node f = qu.front();
qu.pop();
//cout<<f.x<<" "<<f.y<<" "<<f.p<<endl;
if(f.x==0||f.y==0||f.x==n-1||f.y==m-1)
{
flag=1;
re = f.p;
break;
}
for(int i=0;i<4;i++)
{
tmp.x = f.x+dir[i][0];
tmp.y = f.y + dir[i][1];
tmp.p = f.p+1;
if(tmp.x<0||tmp.x>=n||tmp.y<0||tmp.y>=m||maze[tmp.x][tmp.y]<=tmp.p||maze[tmp.x][tmp.y]==-1||vis[tmp.x][tmp.y]==1)continue;
qu.push(tmp);
vis[tmp.x][tmp.y]=1;
}
}
}
int main()
{
int t;
cin>>t;
char tmp;
node st;
node fire;
ios::sync_with_stdio(false);
while(t--)
{
cin>>n>>m;
flag=0;
memset(vis,0,sizeof(vis));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>tmp;
if(tmp == '#')maze[i][j] = -1;
else if(tmp=='.')maze[i][j] = inf;
else if(tmp=='J')
{
maze[i][j] = inf;
st.x = i;
st.y = j;
}
else if(tmp == 'F')
{
maze[i][j]=1;
fire.x = i;
fire.y = j;
quf.push(fire);
}
}
}
bfs1();
bfs2(st);
if(flag==1)cout<<re<<endl;
else cout<<"IMPOSSIBLE"<<endl;
}
return 0;
}