68分求助
  • 板块P2802 回家
  • 楼主Sky_Sea
  • 当前回复0
  • 已保存回复0
  • 发布时间2023/8/20 21:10
  • 上次更新2023/11/3 02:22:23
查看原帖
68分求助
946226
Sky_Sea楼主2023/8/20 21:10
#include<bits/stdc++.h>
using namespace std;
int n,m,sx,sy,fx,fy;
char mat[15][15];
int nxt[4][2]={0,1,0,-1,1,0,-1,0};
int book[15][15];
struct node{
	int x,y,cost,hp;
	friend bool operator < (node a,node b){
		return a.cost>b.cost;
	}
};
priority_queue<node>q;
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=m;j++){
			cin>>mat[i][j];
			if(mat[i][j]=='2')
				sx=i,sy=j;
			if(mat[i][j]=='3')
				fx=i,fy=j;
		}
	}
	memset(book,0,sizeof(book));
	book[sx][sy]=1;
	q.push({sx,sy,0,6});
	while(!q.empty()){
		node tmp=q.top();
		q.pop();
		if(tmp.x==fx && tmp.y==fy){
			cout<<tmp.cost<<endl;
			return 0;
		}
		if(tmp.hp>1){
			for(int i=0;i<4;i++){
				int nx=nxt[i][0]+tmp.x;
				int ny=nxt[i][1]+tmp.y;
				if(nx>=1 && nx<=n && ny>=1 && ny<=m){
					if(mat[nx][ny]=='1' || mat[nx][ny]=='3') {
						if(book[nx][ny]<tmp.hp-1){
							book[nx][ny]=tmp.hp-1;
							q.push({nx,ny,tmp.cost+1,tmp.hp-1});
						}
					}
					if(mat[nx][ny]==4){
						if(!book[nx][ny]){
							book[nx][ny]=1;
							q.push({nx,ny,tmp.cost+1,6});
						}
					}
				}
			}			
		}
	}
	cout<<-1<<endl;
	return 0;
}
2023/8/20 21:10
加载中...