BFS(宽度优先搜索) -例题

原题地址

https://vjudge.net/contest/313171     密码:algorithm

A - Rescue

 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遇到护卫时将杀死他并浪费一分钟时间,所以需要用优先队列。

代码:

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 char arr[200+10][200+10];//存储地牢地图 
 4 int arr1[200+10][200+10];//标记走过的路 
 5 int dx[4]={0,0,1,-1}; 
 6 int dy[4]={1,-1,0,0}; //代表方向 
 7 struct aa{//将数据放入一个结构优先队列中,并按w的大小排序 
 8     int x,y,w;
 9     friend bool operator<(const aa &x,const aa &y){
10         return x.w>y.w;//按照w的升序排列 
11     }
12 }aaa;
13 int bfs(int n,int m,int x1,int y1){
14     memset(arr1,0,sizeof(arr1));//多组输入初始化数组 
15     priority_queue<aa>que;//构建队列 
16     aaa={x1,y1,0};
17     que.push({x1,y1,0});
18     int xx,yy,xxx,yyy,w,s;
19     while(que.size()){
20         xx=que.top().x; 
21         yy=que.top().y;
22         w=que.top().w;//取出队列的top; 
23         arr1[yy][xx]=1;//将初始位置标记 
24         que.pop();//删除top,要现取现删 
25         for(int i=0;i<4;i++){
26             xxx=xx+dx[i];
27             yyy=yy+dy[i];//下一个位置的坐标 
28             if(xxx>=0&&xxx<m&&yyy>=0&&yyy<n&&arr[yyy][xxx]!='#'&&arr1[yyy][xxx]==0){//进行判断 
29                 if(arr[yyy][xxx]=='.'){
30                     que.push({xxx,yyy,w+1});//如果是路w+1,并存入队列 
31                     arr1[yyy][xxx]=1; //标记 
32                 }
33                 else if(arr[yyy][xxx]=='x'){
34                     que.push({xxx,yyy,w+2});//如果是护卫w+2 
35                     arr1[yyy][xxx]=1;//标记 
36                 }
37                 else if(arr[yyy][xxx]=='a'){
38                     return w+1;//等于a说明找到公主,此时所用时间最短,输出 
39                 }
40             }
41         }
42     }
43     return 0;//没找到输出0; 
44 }
45 int main(){
46     int n,m;
47     while(cin>>n>>m){
48         int x,y,ans;
49         for(int i=0;i<n;i++){//构建地牢地图 
50             cin>>arr[i];
51             for(int j=0;j<m;j++){
52                 if(arr[i][j]=='r'){
53                     x=j;
54                     y=i;
55                 }
56             }
57         }
58         ans=bfs(n,m,x,y);
59         if(ans){//判断输出 
60             cout<<ans<<endl;
61         }
62         else{
63             puts("Poor ANGEL has to stay in the prison all his life.");
64         }
65     }
66     return 0;
67     
68 }
View Code

 

B - Red and Black

There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can't move on red tiles, he can move only on black tiles. 
Write a program to count the number of black tiles which he can reach by repeating the moves described above. 

Input

The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20. 
There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows. 

'.' - a black tile 
'#' - a red tile 
'@' - a man on a black tile(appears exactly once in a data set) 

Output

For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).

解题思路:

与上一题大致相同,且可以不用优先队列。

 

C - Battle City

 poj2312 

解题思路与第一题相同

 

D - Catch That Cow

农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不。最少要花多少时间才能抓住牛?

Input

一行: 以空格分隔的两个字母: N 和 K

Output

一行: 农夫抓住牛需要的最少时间,单位分钟

Sample Input

5 17

Sample Output

4

Hint

农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.
解题思路:
走的方向有三种,注意范围。
 

E - Dungeon Master

 Description - 题目描述

[NWUACM] 
你被困在一个三维的空间中,现在要寻找最短路径逃生!
空间由立方体单位构成
你每次向上下前后左右移动一个单位需要一分钟
你不能对角线移动并且四周封闭
是否存在逃出生天的可能性?如果存在,则需要多少时间?

Input - 输入

  输入第一行是一个数表示空间的数量。
  每个空间的描述的第一行为L,R和C(皆不超过30)。
  L表示空间的高度。
  R和C分别表示每层空间的行与列的大小。
  随后L层地牢,每层R行,每行C个字符。
  每个字符表示空间的一个单元。'#'表示不可通过单元,'.'表示空白单元。你的起始位置在'S',出口为'E'。
  每层空间后都有一个空行。L,R和C均为0时输入结束。

Output - 输出

  每个空间对应一行输出。
  如果可以逃生,则输出如下
  Escaped in x minute(s).
  x为最短脱离时间。
  如果无法逃生,则输出如下 :Trapped!

解题思路:

三维与二维相似,将方向改为 int dx[6]={0,0,1,-1,0,0}; int dy[6]={1,-1,0,0,0,0}; int dz[6]={0,0,0,0,1,-1};即可.


F - Robot Motion

 

 A robot has been programmed to follow the instructions in its path. Instructions for the next direction the robot is to move are laid down in a grid. The possible instructions are 

N north (up the page) 
S south (down the page) 
E east (to the right on the page) 
W west (to the left on the page) 
For example, suppose the robot starts on the north (top) side of Grid 1 and starts south (down). The path the robot follows is shown. The robot goes through 10 instructions in the grid before leaving the grid. 
Compare what happens in Grid 2: the robot goes through 3 instructions only once, and then starts a loop through 8 instructions, and never exits. 
You are to write a program that determines how long it takes a robot to get out of the grid or how the robot loops around. 

Input

There will be one or more grids for robots to navigate. The data for each is in the following form. On the first line are three integers separated by blanks: the number of rows in the grid, the number of columns in the grid, and the number of the column in which the robot enters from the north. The possible entry columns are numbered starting with one at the left. Then come the rows of the direction instructions. Each grid will have at least one and at most 10 rows and columns of instructions. The lines of instructions contain only the characters N, S, E, or W with no blanks. The end of input is indicated by a row containing 0 0 0.

Output

For each grid in the input there is one line of output. Either the robot follows a certain number of instructions and exits the grid on any one the four sides or else the robot follows the instructions on a certain number of locations once, and then the instructions on some number of locations repeatedly. The sample input below corresponds to the two grids above and illustrates the two forms of output. The word "step" is always immediately followed by "(s)" whether or not the number before it is 1.

Sample Input

3 6 5
NEESWE
WWWESS
SNWWWW
4 5 1
SESWE
EESNW
NWEEN
EWSEN
0 0 0

Sample Output

10 step(s) to exit
3 step(s) before a loop of 8 step(s)

解题思路:
使用递归遍历走的路,看是否是循环或能否走出去。 
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<math.h>
 5 #include<queue>
 6 #include<algorithm>
 7 #include <vector>
 8 using namespace std;
 9 int n,m;
10 char arr[15][15];
11 int arr1[15][15];
12 int flag=0,l,r,ans;
13 void bfs(int x,int y,int num){
14     if(x<0||y<0||x>=m||y>=n){
15         ans=num;
16         return ;
17     }
18     if(arr1[y][x]){
19         flag=1;
20         l=arr1[y][x];
21         r=num-arr1[y][x];
22         return ;
23     }
24     arr1[y][x]=num;
25     if(arr[y][x] == 'N')
26         bfs(x,y-1,num+1);                
27     else if(arr[y][x] == 'S')
28         bfs(x,y+1,num+1);
29     else if(arr[y][x] == 'E')
30         bfs(x+1,y,num+1);        
31     else if(arr[y][x] == 'W')
32         bfs(x-1,y,num+1); 
33 }
34 int main(){
35     int x,y=0;
36     while(cin>>n>>m>>x){
37         if(n==0&m==0&x==0){
38             break;
39         }
40         flag=0;
41         y=0;
42         x=x-1;
43         memset(arr1,0,sizeof(arr1));
44         for(int i=0;i<n;i++){
45             cin>>arr[i];
46         }
47         bfs(x,y,1);
48         if(flag){
49             printf("%d step(s) before a loop of %d step(s)\n",l-1,r);
50         }
51         else {
52             printf("%d step(s) to exit\n",ans-1);
53         }
54     }
55     return 0;
56 }
View Code

 

G - Number Transformation

In this problem, you are given an integer number s. You can transform any integer number A to another integer number B by adding x to A. This x is an integer number which is a prime factor of A (please note that 1 and A are not being considered as a factor of A). Now, your task is to find the minimum number of transformations required to transform s to another integer number t.

Input

Input starts with an integer T (≤ 500), denoting the number of test cases.

Each case contains two integers: s (1 ≤ s ≤ 100) and t (1 ≤ t ≤ 1000).

Output

For each case, print the case number and the minimum number of transformations needed. If it's impossible, then print -1.

Sample Input

2

6 12

6 13

Sample Output

Case 1: 2

Case 2: -1

解题思路:

a的prime factor(素因子)是指能整除a且不是素数的数字i,i!=1&&i!=a.本题的意思是循环一个数,这个数加上他的素因子,直到与给出的另一个数相等位置(数在改变,所以素因子也在改变)。

代码:

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<iostream>
 4 #include<math.h>
 5 #include<queue>
 6 #include<algorithm>
 7 #include <vector>
 8 using namespace std;
 9 typedef pair<int,int> P;
10 vector<int>arr;
11 int arr1[1000];
12 int is_primer(int a){
13     if(a==2)return 1;
14     for(int i=2;i<a;i++){
15         if(a%i==0){
16             return 0;
17         }
18     }
19     return 1;
20 }
21 int bfs(int a,int b){
22     memset(arr1,0,sizeof(arr1));
23     queue<P>que;
24     int d,ss;
25     que.push({a,0});
26     arr1[a]=1;
27     while(que.size()){
28         arr.clear();
29         int x,y;
30         x=que.front().first;
31         y=que.front().second;
32         for(int j=2;j<x;j++){
33             if(x%j==0&&is_primer(j)){
34                 arr.push_back(j);
35             }
36         }
37         que.pop();
38         for(int i=0;i<arr.size();i++){
39             d=x+arr[i];
40             if(d>0&&d<b+1&&!arr1[d]){
41                 if(d==b){
42                     return y+1;
43                 }
44                 else{
45                     que.push({d,y+1});
46                     arr1[d]=1;
47                 }
48             }
49         }
50     }
51     return 0;
52 }
53 int main(){
54     int n,s,k=0,t;
55     cin>>n;
56     for(int i=1;i<=n;i++){
57         k=0;
58         cin>>s>>t;
59         if(s==t){
60             printf("Case %d: 0\n",i);
61         }
62         else{
63             int ans=bfs(s,t);
64             printf("Case %d: ",i);
65             if(ans){
66                 cout<<ans<<endl;
67             }
68             else {
69                 cout<<-1<<endl;
70             }
71         }
72     }
73     return 0;
74 }
View Code

 

H - Knight Moves

A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy. 
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part. 

Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b. 

Input

The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard. 
Output

For each test case, print one line saying "To get from xx to yy takes n knight moves.". 
Sample Input

e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6

Sample Output

To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.

 解题思路:

题意大致是从一个点到另一个点以走'日'的形式需要的最短时间,一共有八个方向。

代码略。

 






posted @ 2019-07-23 22:43  yya雨  阅读(811)  评论(0编辑  收藏  举报