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(广度优先搜索)算法来求解无向图的最大团的 C 代码实现: ``` #include <stdio.h> #include <stdlib.h> #define N 100 // 最大顶点 int G[N][N], visit[N], cur[N], max[N], max_size = 0; // G: 无向图邻接矩阵, visit: DFS 中的访问组 // cur:当前团中的节点集合,max:当前最大团中的节点集合,max_size:当前最大团的大小 // 判断一个节点集合是否与给定的节点 u 相邻 int check_v(int u, int cur_size) { int i; for (i = 0; i < cur_size; ++i) { if (!G[u][cur[i]]) { return 0; } } return 1; } // 判断一个团是否为最大团 void check_max(int cur_size) { if (cur_size > max_size) { // 如果当前团更大,则更新最优解 int i; for (i = 0; i < cur_size; ++i) { max[i] = cur[i]; } max_size = cur_size; } } // 使用 BFS(广度优先搜索)算法来求最大团 void max_clique_bfs() { int cur_size, u, v, i, j, tail = 0; int queue[N]; // 队列 for (i = N - 1; i >= 0; --i) { // 倒序遍历顶点 cur_size = 1; cur[0] = i; // 当前的团中只有一个节点 i queue[tail++] = i; // 把 i 放入队列 while (tail > 0) { // BFS 基本结构,依次访问队列中的节点 u = queue[--tail]; for (v = 0; v < N; ++v) { if (G[u][v] && !visit[v] && check_v(v, cur_size)) { // 以 BFS 的方式依次遍历所有与 u 相邻的节点 v visit[v] = 1; cur[cur_size++] = v; // 把 v 加入当前的团中 queue[tail++] = v; // 把 v 放入队列 } } } check_max(cur_size); // 检查当前生成的团是否为最大团 max[i] = -1; max_size = 0; } } int main() { int n, m, i, j; scanf("%d%d", &n, &m); // n 为顶点,m 为边 for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { G[i][j] = 0; // 初始化邻接矩阵为 0 } } for (i = 0; i < m; ++i) { int u, v; scanf("%d%d", &u, &v); // 读入边 --u; --v; // 将节点编号转化为从 0 开始的编号 G[u][v] = G[v][u] = 1; // 如果 u 和 v 相邻,则 G[u][v] 和 G[v][u] 均为 1 } max_clique_bfs(); // 求解最大团 printf("Size of maximum clique is %d\n", max_size); printf("Vertices in the maximum clique are: "); for (i = 0; i < max_size; ++i) { printf("%d ", max[i] + 1); // 将最优解中节点的编号重新转化为从 1 开始的编号输出 } printf("\n"); return 0; } ``` 以上代码实现了使用 BFS(广度优先搜索)算法来求解无向图的最大团。算法的基本思路是从图中的每一个节点开始,依次生成每一个包含该节点的团,并检查其是否为最大团。为了避免重复,当遍历一个节点 u 时,只考虑它的编号比 u 更大的节点 v 作为当前团的元素,这样可以保证每个团只被遍历一次。在判断一个节点集合是否与给定的节点 u 相邻时,只需要检查这些节点之间是否存在边即可。由于 BFS 算法遍历顺序是按照层依次访问所有节点,因此可以保证通过 BFS 算法所生成的团一定是最大团中的一员。最后,只需要从所有最大团中选择一个节点最多的团作为最优解即可。 注意:上面代码中的变量 G 是一个邻接矩阵,其中 G[u][v] 和 G[v][u] 分别表示节点 u 和节点 v 是否相邻。在使用该代码时,需要将图中的所有节点编号都减一,以满足组下标从 0 开始的要求。另外,由于该算法的时间复杂度为 O(2^n),因此只适用于节点不太多(通常小于 40)的图。如果节点过多,则建议使用其他的算法,例如 Bron-Kerbosch 算法等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值