1 solutions

  • 0
    @ 2022-8-28 19:03:17

    用两个队列 一个用来正常前进,一个用来看传送过去有没有用

    #include<bits/stdc++.h>
    using namespace std;
    char ma[250][250];
    bool v[250][250];
    int dx[]={1,-1,0,0},dy[]={0,0,1,-1};
    int n,m,sx,sy,ex,ey,ans=-1,temp=1e5;
    struct point
    {
    	int x,y,t;
    };
    queue<point> q;
    queue<point> a;//传送后的;
    void find(int x,int y,int t)
    {
    	bool A[250][250]={0};
    	a.push((point){ex,ey,0});
    	A[ex][ey]=1;
    	A[x][y]=1;
    	while(!a.empty())
    	{
    		point w=a.front();
    		a.pop();
    		if(ma[w.x][w.y]=='@')
    		{
    			temp=w.t+t;
    			return;
    		}
    		for(int i=0;i<4;i++)
    		{
    			int xx=w.x+dx[i];
    			int yy=w.y+dy[i];
    			if(xx>=0&&yy>=0&&yy<m&&xx<n&&ma[xx][yy]!='#'&&!A[xx][yy])
    			{
    				A[xx][yy]=1;
    				a.push((point){xx,yy,w.t+1});
    			}
    		}
    	}
    	
    }
    void bfs(int x,int y)
    {
    	int tp=1;
    	q.push((point){x,y,0});
    	v[x][y]=1;
    	while(!q.empty())
    	{
    		point now=q.front();
    		q.pop();
    		if(ma[now.x][now.y]=='P')
    		{
    		//	cout<<now.t<<" "<<temp<<endl;
    			ans=min(now.t,temp); 
    			return;
    		}
    		if(ma[now.x][now.y]=='@'&&tp)
    		{
    			find(now.x,now.y,now.t);
    			tp=0;
    		}
    		for(int i=0;i<4;i++)
    		{
    			int xx=now.x+dx[i];
    			int yy=now.y+dy[i];
    			if(xx>=0&&yy>=0&&yy<m&&xx<n&&ma[xx][yy]!='#'&&!v[xx][yy])
    			{
    				v[xx][yy]=1;
    				q.push((point){xx,yy,now.t+1});
    			}
    		}
    	}
    }
    int main()
    {
    	cin>>n>>m;
    	for(int i=0;i<n;i++)
    	{
    		cin>>ma[i];
    		for(int j=0;j<m;j++)
    		{
    			if(ma[i][j]=='S') sx=i,sy=j;
    			else if(ma[i][j]=='P') ex=i,ey=j;
    		}
    	}
    	bfs(sx,sy);
    	cout<<ans;
    	return 0;
     }
    

    Information

    ID
    6539
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    3
    Tags
    # Submissions
    43
    Accepted
    8
    Uploaded By