PTA7-11 拯救行动
一、题目描述

二、解题思路
这题是经典的bfs题,但是因为这个守卫每次都会多用掉1个时间,但是我们bfs每次只会扩展一步,所以就会提前到达终点,但是不是最优解的情况
比如说下面这种情况

我们都知道两点之间直线最短。但是这个直线上的士兵这么多,最后花费的时间可能会比走弯道更多。所以我们的解决方法是,设置一个距离数组,如果这个距离被松弛了的话,就把这个点就如距离。然后跑完整个bfs,打印公主坐标的距离即可。
三、代码实现
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 using namespace std; 6 const int maxn=210; 7 char mp[maxn][maxn]; 8 int n,m,x1,y1; 9 int dir[4][2]={-1,0,1,0,0,-1,0,1},vis[maxn][maxn]; 10 11 struct Maze{ 12 int x,y; 13 int step; 14 bool operator<(const Maze &m)const{ 15 return step>m.step; 16 } 17 Maze(int x,int y,int s): x(x),y(y),step(s){} 18 }; 19 20 int bfs(int x,int y){ 21 priority_queue<Maze > pq; 22 pq.push(Maze(x,y,0)); 23 24 while(!pq.empty()){ 25 int tmp_x=pq.top().x; 26 int tmp_y=pq.top().y; 27 int tmp_step=pq.top().step; 28 pq.pop(); 29 //cout<<"tmp.x="<<tmp.x<<",tmp.y="<<tmp.y<<",tmp.step="<<tmp.step<<",mp[tmp.x][tmp.y]="<<mp[tmp.x][tmp.y]<<endl; 30 //if(mp[tmp.x][tmp.y]=='a') return tmp.step; 31 32 for(int i=0;i<4;i++){ 33 int dx=tmp_x+dir[i][0]; 34 int dy=tmp_y+dir[i][1]; 35 if(dx<0||dy<0||dx>=n||dy>=m) continue; 36 37 if(!vis[dx][dy]){ 38 vis[dx][dy]=1; 39 if(mp[dx][dy]=='@'){ 40 pq.push(Maze(dx,dy,tmp_step+1)); 41 }else if(mp[dx][dy]=='x'){ 42 pq.push(Maze(dx,dy,tmp_step+2)); 43 }else if(mp[dx][dy]=='a'){ 44 return tmp_step+1; 45 } 46 } 47 } 48 } 49 return -1; 50 } 51 52 53 int main(){ 54 int s; 55 scanf("%d",&s); 56 while(s--){ 57 scanf("%d%d",&n,&m); 58 for(int i=0;i<n;i++){ 59 scanf("%s",mp[i]); 60 } 61 int x=-1,y; 62 for(int i=0;i<n;i++){ 63 if(x!=-1) break; 64 for(int j=0;j<m;j++){ 65 if(mp[i][j]=='r'){ 66 x=i;y=j; 67 } 68 } 69 } 70 memset(vis,0,sizeof(vis)); 71 int ans=bfs(x,y); 72 if(ans==-1) 73 printf("Impossible\n"); 74 else 75 printf("%d\n",ans); 76 } 77 return 0; 78 }
本文来自博客园,作者:{scanner},转载请注明原文链接:{https://home.cnblogs.com/u/scannerkk/}

浙公网安备 33010602011771号