1 solutions

  • 0
    @ 2022-3-8 20:14:33

    记忆化深度优先搜索,注意判断条件

    #include <bits/stdc++.h>
    using namespace std;
    int sx,sy,ex,ey;
    int n,m;
    int dx[]={0,0,1,-1};
    int dy[]={1,-1,0,0};
    int val[13][13];
    int b[13][13];//存血量
    int a[13][13];//存步数
    struct pre{
    	int x,y,sum,bushu;
    };
    void bfs(){
    	queue<pre>q;
    	q.push({sx,sy,6,0});
    	while(!q.empty()){
    		for(int i=0;i<4;i++){
    			int nx=q.front().x+dx[i],ny=q.front().y+dy[i];
    			if(nx>0&&nx<=n&&ny>0&&ny<=m&&a[nx][ny]!=0&&(val[q.front().x][q.front().y]+1<val[nx][ny]||b[nx][ny]<q.front().sum-1)&&q.front().sum>1){
    				val[nx][ny]=min(q.front().bushu+1,val[nx][ny]);
    				b[nx][ny]=max(b[nx][ny],q.front().sum-1);
    				if(a[nx][ny]==4){
    					b[nx][ny]=6;
    					q.push({nx,ny,6,q.front().bushu+1});
    				}
    				else q.push({nx,ny,q.front().sum-1,q.front().bushu+1});
    			}
    		}
    		q.pop();
    	}
    }
    int main(){
    	cin>>n>>m;
    	memset(val,0x3f3f3f3f,sizeof(val));
    	memset(b,-1,sizeof(b));
    	for(int i=1;i<=n;i++){
    		for(int j=1;j<=m;j++){
    			cin>>a[i][j];
    			if(a[i][j]==2){
    				sx=i,sy=j;
    				val[sx][sy]=0;
    				b[sx][sy]=6;
    			}
    			else if(a[i][j]==3){
    				ex=i,ey=j;
    			}
    		}
    	}
    	bfs();
    	if(val[ex][ey]==0x3f3f3f3f) puts("-1");
    	else cout<<val[ex][ey];
    	return 0;
    }
    • 1

    Information

    ID
    1250
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    9
    Tags
    # Submissions
    21
    Accepted
    2
    Uploaded By