Rescue BFS

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/dujuancao11/article/details/81148391

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.

Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)

 

Input

 

First line contains two integers stand for N and M.

Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.

Process to the end of the file.

 

Output

 

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life."

 

Sample Input

 

7 8 
#.#####. 
#.a#..r. 
#..#x... 
..#..#.# 
#...##.. 
.#...... 
........

 

Sample Output

 

13

菜鸟分析:让r救a么 ,但是r有很多个,你就从a开始找最近的r,测试案例比较特殊,他正好有一个朋友,容易误导,每个朋友有好几种营救方法,要找到离他最近的朋友,再从这些路中找出最短的。

测试案例

这条蓝色的是最短的 蓝色的加上杀警卫的时间+1=13,红色的=14

最短路径问题BFS?

(谢谢大佬)参考题解https://blog.csdn.net/u013923947/article/details/2317421

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
int n,m;
int xa,ya,xr,yr;
char map[220][220];
int vis[220][220];
int dis[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct node
{
    int x,y,step;
    bool operator < (const node& t)const{
        return step>t.step;
    }
};
int  bfs()
{
    memset(vis,0,sizeof(vis));
    priority_queue<node>q;
    node f;
    f.x=xa;
    f.y=ya;
    f.step=0;
    vis[xa][ya]=1;
    q.push(f);
    while(!q.empty())
    {
        f=q.top();
        q.pop();
        if(map[f.x][f.y]=='r')
        {
          return f.step;
        }
        // 朋友不只是一个,而天使却是一个,所以我们可以反过来寻找,天使找朋友,那么目标状态就是找到朋友
        for(int i=0;i<4;i++)
        {
        node next;
        int xi=f.x+dis[i][0];
        int yi=f.y+dis[i][1];
            if(xi>=0 &&xi<n && yi>=0 && yi<m && map[xi][yi]!='#' && !vis[xi][yi])
            {
                vis[xi][yi]=1;
                next.x=xi;
                next.y=yi;
                if(map[xi][yi]=='x')
                    next.step=f.step+2;
                else
                    next.step=f.step+1;
                q.push(next);
            }
        }
    }
    return -1;
}
int main()
{
    while(cin>> n >> m)
    {

      for(int i=0;i<n;i++)
      {
        scanf("%s",map[i]);
        for(int j=0;j<m;j++)
    {
        if(map[i][j]=='a')
        {
            xa=i;
            ya=j;
        }
    }
    }
   int ans=bfs();
    if(ans==-1)
        printf("Poor ANGEL has to stay in the prison all his life.\n");
    else
        printf("%d\n",ans);
  }

    return 0 ;
}

以下是错误代码只作参考

#include<iostream> 
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

int n,m;
char map[205][205];
int vis[205][205];
/*两个作用
1.标记作用,刚开始初始化为1,先将起始点初始化为0,以防回到起点 
2.记录当前点的最短路径 
*/
int x1,x2,y1,y2;
int mov[][2] = {1,0,-1,0,0,1,0,-1};

struct node
{
    int x,y,step;
    //友元函数 重载<
    //优先队列就是node型的  在优先队列里按照step排序
    friend bool operator<(node n1,node n2)
    {
        return n2.step<n1.step;
    }
};

int place(int x,int y)
{
    if(x<0 || y<0 || x>=n || y>=m || !vis[x][y] || map[x][y] == '#')
        return 1;//出界或者为墙
    return 0;
}

int bfs()
{
    int i;
    priority_queue<node> Q;//优先队列
    node a,next;
    a.x = x1;
    a.y = y1;
    a.step = 0;
    Q.push(a);//进队
    vis[x1][y1] = 0;//初始化
    while(!Q.empty())
    {
        a = Q.top();//队头
        Q.pop();//出队
        if(a.x == x2 && a.y == y2)
            return a.step;
            //四个方向
        for(i = 0; i<4; i++)
        {
            next = a;//移动后的结点
            next.x+=mov[i][0];
            next.y+=mov[i][1];
            if(place(next.x,next.y))//判断 走不通
                continue;//跳出当前循环
            next.step++;//每动一次要加1
            if(map[next.x][next.y] == 'x')//卫兵处多花费了一秒
                next.step++;
            if(vis[next.x][next.y]>=next.step)//存入最小时间
            {
                vis[next.x][next.y] = next.step;//第二个作用 更新最小 
                Q.push(next);
            }//只有起点标记,其它点未标记只是最小值,还可以走 
        }
    }
    return 0;
}

int main()
{
    while(cin>>n>>m)
    {
        for(int i = 0; i<n; i++)
        {
            scanf("%s",map[i]);
            for(int j = 0; map[i][j]; j++)
            {
                if(map[i][j] == 'r')
                {
                    x1 = i;
                    y1 = j;
                }
                else if(map[i][j] == 'a')
                {
                    x2 = i;
                    y2 = j;
                }
            }
        }
        memset(vis,1,sizeof(vis));
        int ans = 0;
        ans = bfs();
        if(ans)
            printf("%d\n",ans);
        else
            printf("Poor ANGEL has to stay in the prison all his life.\n");
    }

    return 0;
}//Time Limit Exceeded

 

展开阅读全文

Rescue

08-29

The princess is trapped in a magic place. In this place, there are N magic stones. In order to rescue the princess, you should destroy all the stones.nnThe N stones are in a straight line. We number them as s1, s2, ... sn from left to right. Each stone has a magic strength m1, m2, ... mn. You have a powerful skill that can do some damage to the stones. To release the skill, you should stand to the right of some stone (si). Then you throw a power ball towards left. Initially, this ball has a power of p. When it hits a stone, it will do some damage to the stone and its power will be decreased, and the ball will continue to fly left to the next stone if its power is still positive. Formally, if you stand to the right of si and the power ball's initial power is p, then the ball will do Max(0, p - (i - j) * (i - j)) damage to sj, for each j <= i. So from this formula, we can see that the damage to stone sj is only determined by the initial power of the ball and the number of stones between si and sj.nnA stone is destroyed if the accumulated damage you do is larger than its magic strength. Note that even if a stone is destroyed, it will not disappear; your magic ball will do damage to it and the power will be decreased by that stone. You are not strong enough so that you can release at most k magic balls. It will cost a lot of energy if the power of the magic ball is too high. So what is the minimum value of p with which you can destroy all the magic stones, with no more than k magic balls? You can choose where to release each magic ball as your will, and the power of the ball must be a positive integer.nnInputnnThe first line is the number of cases T (T ≤ 100). For each case, the first line gives two integers n, k (1 ≤ n ≤ 50000, 1 ≤ k ≤ 100000). The second line are n integers, giving m1, m2, ... mn (1 ≤ mi ≤ 109).nnOutputnnPrint minimum possible p in a line.nnSample Inputnn2n1 1n1n3 1n1 4 5nSample Outputnn2 问答

Rescue the Rabbit

08-29

Dr. X is a biologist, who likes rabbits very much and can do everything for them. 2012 is coming, and Dr. X wants to take some rabbits to Noah's Ark, or there are no rabbits any more.nnA rabbit's genes can be expressed as a string whose length is l (1 ≤ l ≤ 100) containing only 'A', 'G', 'T', 'C'. There is no doubt that Dr. X had a in-depth research on the rabbits' genes. He found that if a rabbit gene contained a particular gene segment, we could consider it as a good rabbit, or sometimes a bad rabbit. And we use a value W to measure this index.nnWe can make a example, if a rabbit has gene segment "ATG", its W would plus 4; and if has gene segment "TGC", its W plus -3. So if a rabbit's gene string is "ATGC", its W is 1 due to ATGC contains both "ATG"(+4) and "TGC"(-3). And if another rabbit's gene string is "ATGATG", its W is 4 due to one gene segment can be calculate only once.nnBecause there are enough rabbits on Earth before 2012, so we can assume we can get any genes with different structure. Now Dr. X want to find a rabbit whose gene has highest W value. There are so many different genes with length l, and Dr. X is not good at programming, can you help him to figure out the W value of the best rabbit.nnInputnnThere are multiple test cases. For each case the first line is two integers n (1 ≤ n ≤ 10),l (1 ≤ l ≤ 100), indicating the number of the particular gene segment and the length of rabbits' genes.nnThe next n lines each line contains a string DNAi and an integer wi (|wi| ≤ 100), indicating this gene segment and the value it can contribute to a rabbit's W.nnOutputnnFor each test case, output an integer indicating the W value of the best rabbit. If we found this value is negative, you should output "No Rabbit after 2012!".nnSample Inputnn2 4nATG 4nTGC -3nn1 6nTGC 4nn4 1nA -1nT -2nG -3nC -4nSample Outputnn4n4nNo Rabbit after 2012! 问答

FDNY to the Rescue!

08-08

DescriptionnnThe Fire Department of New York (FDNY) has always been proud of their response time to fires in New York City, but they want to make their response time even better. To help them with their response time, they want to make sure that the dispatchers know the closest firehouse to any address in the city. You have been hired to write this software and are entrusted with maintaining the proud tradition of FDNY. Conceptually, the software will be given the address of the fire, the locations of the firehouses, street intersections, and the time it takes to cover the distance between each intersection. It will then use this information to calculate how long it takes to reach an address from each firehouse. nnGiven a specific fire location in the city, the software will calculate the time taken from all the fire stations located in the city to reach the fire location. The list of fire stations will be sorted from shortest time to longest time. The dispatcher can then pick the closest firestation with available firefighters and equipment to dispatch to the fire.nInputnnLine 1: n# of intersections in the city, a single integer (henceforth referred to as N) N<20 nnLines 2 to N+1: nA table (square matrix of integer values separated by one or more spaces) representing the time taken in minutes between every pair of intersections in the city. In the sample input shown below the value "3" on the 1st row and the 2nd column represents the time taken from intersection #1 to reach intersection #2. nnSimilarly the value "9" on the 4th row and the 2nd column represents the time taken from intersection #4 to reach intersection #2. nnA value of -1 for time means that it is not possible to go directly from the origin intersection (row #) to the destination intersection (column #). All other values in the table are non-negative. nnLine N+2: nAn integer value n (<= N) indicating the intersection closest to the fire location followed by one or more integer values for the intersections closest to the fire stations (all on one line, separated by one or more spaces) will follow the input matrix. nnNotes on input format: nn1. The rows and columns are numbered from 1 to N. n2. All input values are integers n3. All fire locations are guaranteed reachable from all firehouses. n4. All distance calculations are made from the intersection closest to each firehouse to the intersection closest to the fire. nOutputnnLine 1: nA label line with the headings for each column, exactly as shown in the example. nnLine 2 onwards (one line for each fire station): nA sorted list (based on time) showing the fire station (origin), the destination site, time taken and a complete shortest path of nodes from the originating fire station to the fire location. nnNotes on output format: n1. Columns are tab separated. n2. If two or more firehouses are tied in time they can be printed in any order. n3. If more than one path exists that has the same minimal time for a given location & firehouse, either one can be printed on the output. n4. If the fire location and the fire station locations happen to be the same intersection, the output will indicate that the origin and destination have the same intersection number, the time will be "0" and the nodes in the shortest path will show just one number, the fire location. nNext is the picture for the sample input data. n![](http://poj.org/images/1122/1122_1.gif)nSample Inputnn6 n0 3 4 -1 -1 -1 n-1 0 4 5 -1 -1 n2 3 0 -1 -1 2 n8 9 5 0 1 -1 n7 2 1 -1 0 -1 n5 -1 4 5 4 0 n2 4 5 6 nIn the above input the last line indicates that "2" is the location of the fire and "4", "5" and "6" are the intersections where fire stations are located. nSample OutputnnOrg Dest Time Pathn5 2 2 5 2n4 2 3 4 5 2n6 2 6 6 5 2 问答

没有更多推荐了,返回首页