BFS 搜索 写代码思路(顺序)

#include <iostream>
#include <queue>
using namespace std;
queue<int> qu;
void bfs()
{

    while(!qu.empty())//只要队列不为空就往下搜索
    {
        int s = qu.front(); //取出队列最前面的元素
        if(满足终止条件)break;//找到终点,跳出队列
        qu.pop();//此元素不满足终止条件,把此元素从队列里弹出来丢掉

        //分方向扩展,把可以走的路(元素)压到队列里
        for(几个方向)
        {
            int next = 下一步;
            if(next满足题目的的各种限制条件 && next是以前没有走过的路)//常用状态数组判断state[next] != 初值
            {
                qu.push(next);//把next压入队列;
                state[next] = 修改值(或者是从起点走来这一步的步数);//修改状态,表示这条路已经走过。
            }
        }
    }
    if(!qu.empty())//如果队列不为空,说明是队列里元素满足了终止条件,
        cout<<结果(最优解)<<endl;
    else
        cout<<"无解"<<endl;
}

int main()
{
    bfs();
    return 0;
}

基本上思路就是这样,一步一步来,题目不同,队列里的元素不同。有些做法也会不同

题目hdu1548

A strange lift

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 21631    Accepted Submission(s): 7913

Problem Description There is a strange lift.The lift can stop can at every floor as you want, and there is a number Ki(0 <= Ki <= N) on every floor.The lift have just two buttons: up and down.When you at floor i,if you press the button “UP” , you will go up Ki floor,i.e,you will go to the i+Ki th floor,as the same, if you press the button “DOWN” , you will go down Ki floor,i.e,you will go to the i-Ki th floor. Of course, the lift can’t go up high than N,and can’t go down lower than 1. For example, there is a buliding with 5 floors, and k1 = 3, k2 = 3,k3 = 1,k4 = 2, k5 = 5.Begining from the 1 st floor,you can press the button “UP”, and you’ll go up to the 4 th floor,and if you press the button “DOWN”, the lift can’t do it, because it can’t go down to the -2 th floor,as you know ,the -2 th floor isn’t exist.

Here comes the problem: when you are on floor A,and you want to go to floor B,how many times at least he has to press the button “UP” or “DOWN”?

 

Input The input consists of several test cases.,Each test case contains two lines.

The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) which describe above,The second line consist N integers k1,k2,….kn.

A single 0 indicate the end of the input.  

Output For each case of the input output a interger, the least times you have to press the button when you on floor A,and you want to go to floor B.If you can’t reach floor B,printf “-1”.  

Sample Input


5 1 5 3 3 1 2 5 0  

Sample Output


3   AC答案:

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

struct node
{
    int lou;
    int step;
};

int main()
{
    int i,n,a,b,h[201],z[201],next;
    queue<node> qu;
    node start,temp;
    while(cin>>n && n!=0)
    {
        cin>>a>>b;
        while(!qu.empty())//清空
            qu.pop();
        for(i = 1; i <= n; i++)//输入每层的数字
        {
            cin>>h[i];
            z[i] = 0;
        }
        start.lou  = a;
        start.step = 0;
        qu.push(start);
        z[start.lou] = 1;
        while(!qu.empty())
        {
            temp = qu.front();
            if(temp.lou == b)break;
            qu.pop();
            next = temp.lou + h[temp.lou];
            if(next <= n && z[next] == 0 )
            {
                start.lou = next;
                start.step = temp.step+1;
                qu.push(start);
                z[next] = 1;
            }
            next = temp.lou - h[temp.lou];
            if(next > 0 && z[next] == 0 )
            {
                start.lou = next;
                start.step = temp.step+1;
                qu.push(start);
                z[next] = 1;
            }
        }
        if(!qu.empty())
            cout<<qu.front().step<<endl;
        else
            cout<<"-1"<<endl;
    }
    return 0;
}

hdu 2717

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12524    Accepted Submission(s): 3872

Problem Description Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.

* Walking: FJ can move from any point X to the points X – 1 or X + 1 in a single minute

* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.

If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?  

Input Line 1: Two space-separated integers: N and K  

Output Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.  

Sample Input


5 17  

Sample Output


4
Hint The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.
  AC答案:

#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
void bfs(int n,int k)
{
    int s = n,x;
    int state[100001] = {0};
    queue<int> qu;
    state[s] = 1;
    qu.push(s);
    while(!qu.empty())
    {
        x = qu.front();

        if(x == k)break;
        qu.pop();
        if( 2*x <= 100000 && state[2*x] == 0)
        {
           qu.push(2*x);
           state[2*x] = state[x] + 1;
        }
        if(0 <= x -1 && state[x-1] == 0)
        {
           qu.push(x-1);
           state[x-1] = state[x] + 1;
        }
        if(x+1 <= 100000 && state[x+1] == 0)
        {
           qu.push(x+1);
           state[x+1] = state[x] + 1;
        }
    }
    cout<<state[k] - 1<<endl;
}
int main()
{
    int n,k;
    while(cin>>n>>k)
    {
       bfs(n,k);
    }
    return 0;
}

hdu 1372


Knight Moves

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10344    Accepted Submission(s): 6084

Problem Description 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.

AC答案:

#include <iostream>
#include <queue>
#include <string>
using namespace std;
int st[8][2]={
{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}
};
struct node
{
    int x,y;
    int step;
    bool operator ==(node n)
    {
        return this->x == n.x && this->y == n.y;
    }
}start,tend,temp,newnode;
int sx,sy,ex,ey;

bool ju(int x,int y)
{
    return x>=1 && x<=8 && y>=1 && y<=8;
}

int bfs()
{
    int step,i,nx,ny;
    bool state[9][9]={false};
    queue<node> qu;
    qu.push(start);
    start.step = 0;
    state[start.x][start.y] = true;
    while(!qu.empty())
    {
        temp = qu.front();
        //cout<<temp.x<<" "<<temp.y<<endl;
        if(temp == tend)
            break;
        qu.pop();
        for(i = 0;i < 8;i++)
        {
            nx = temp.x + st[i][0];
            ny = temp.y + st[i][1];
            if(ju(nx,ny) && state[nx][ny] == false)
            {
                newnode.x = nx;
                newnode.y = ny;
                newnode.step = temp.step + 1;
                state[nx][ny] = true;
                qu.push(newnode);
            }
        }
    }
    if(!qu.empty())
        step = qu.front().step;
    else step = -1;
    return step;
}

int main()
{
    char p1[3],p2[3];
    while(cin>>p1>>p2 && p1[0]!='\0' && p1[0]!='\0')
    {
        start.x = p1[0]-'a'+1,start.y = p1[1] - '0';
        tend.x = p2[0]-'a'+1,tend.y = p2[1] - '0';
        //cout<<sx<<" "<<sy<<" "<<ex<<" "<<ey<<endl;
        cout<<"To get from "<<p1<<" to "<<p2<<" takes "<<bfs()<<" knight moves."<<endl;
    }
    return 0;
}

    原文作者:BFS
    原文地址: https://blog.csdn.net/hynuhuanghao/article/details/52214771
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞