DFS和BFS搜素算法
假设有9个点,未知每个点的可行性,我们要去搜索一条可能的路径
一 BFS(广度优先搜索)
1.简介
若用BFS去搜索,则顺序为
次数 | 节点 |
---|---|
1 | 1 |
2 | 2 3 4 |
3 | 5 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;
}