搜索算法——DFS和BFS

  DFS和BFS搜素算法

 假设有9个点,未知每个点的可行性,我们要去搜索一条可能的路径
在这里插入图片描述

一 BFS(广度优先搜索)

1.简介

 若用BFS去搜索,则顺序为

次数节点
11
22 3 4
35 6 7 8 9

 若某个节点为不可行,那么不对他的子节点进行搜索,在搜索时同一层次的一起搜索,结束后进入下一层中可行的节点
 在C++中实现BFS可以借助queue,实现进栈和出栈的操作,搜索完一个节点后,就把他删除,同时加入他可行的子节点

2.下面来看一道题

在这里插入图片描述

#include <iostream>
#include <queue>
#include <map>
#include <string>
using namespace std;
struct node
{
    string str;
    int step;
};
string a,b;
string Start[10];
string End[10];
int n,ans; // use n to record the number of the method of translating
map<string, int>Map; //use map to record the string that has been searched
queue<node>all;
string change(string str,int i,int j)
{
    string Ans="";
    if(i+Start[j].length() > str.length())
        return Ans;
    for (int x = 0; x<Start[j].length(); x++)
    {
        if(str[i+x] != Start[j][x])
        return Ans;
    }
    Ans = str.substr(0,i);
    Ans += End[j];
    Ans += str.substr(i+Start[j].length());
    return Ans;
}
void BFS()
{
    node init;
    init.step = 0; //initialize
    init.str = a;
    all.push(init);
    while (!all.empty())
    {
        //if the queue isn't empty, continue
        node temp1 = all.front();
        all.pop();
        // del this point
        if(Map.count(temp1.str) == 1) continue;
            Map[temp1.str]=1;
        if(temp1.str == b)
        {
            ans = temp1.step;
            break;
        }
        string sentence;
        string temp;
        sentence = temp1.str;
        for (int i = 0; i < sentence.length(); i++)
        {
            for (int j = 0; j < n; j++)
            {
                //change the string according to the changing rules
                temp = change(sentence, i, j);
                if(temp != "")
                {
                    node temp2;
                    temp2.str = temp;
                    temp2.step = temp1.step + 1;
                    all.push(temp2);
                    // get in the childpoint
                }
            }
        }
    }
    if(ans == 0||ans > 10)
        printf("NO ANSWER!");
    else
        printf("%d",ans);
}
int main()
{
    cin>>a>>b;
    while (cin>>Start[n]>>End[n]) n++;
    BFS();
    return 0;
}

DFS稍后更新

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值