前言
因有些小伙伴评论说我一些搜索优化没讲到,所以我不介意再水一期。
第五个优化:双向BFS
双向BFS还是有点用的。
上期说过,双向搜索适用于有初态与有终态的搜索中。
双向BFS是这样搜的。
-
定义两个队列
q1与q2。 -
将起点加入
q1,终点加入q2。 -
交替扩散
q1与q2。 -
如果
q1为空或者q2为空,结束搜索。(没搜索到答案) -
如果某个点
q1与q2都访问到了,说明经过那个点有最优答案路径。(搜索到了最优答案) -
因情况判断重复
就那么简单,接下来看例题。
又是这题,这题可以用双向BFS解的。
主要是它的移动的权值都为 1。
经计算,用普通 BFS 的最高复杂度达到 ,不能过。(要过也得加剪枝)
经计算,用双向 BFS 的最高复杂度达到 ,能过的。
代码。
#include<bits/stdc++.h>
using namespace std;
struct node{
int a[3][3];
int step;
const int* operator [] (const int &x)const{
return a[x];
}
void input(){
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
scanf("%1d",&a[i][j]);
step=0;
}
node(){
int p[3][3]={1,2,3,8,0,4,7,6,5};
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j]=p[i][j];
step=0;
}
string to_string(){
string s="";
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
s+=a[i][j]+'0';
return s;
}
}st;
unordered_map<string,pair<int,int> >mp;
bool operator == (node x,node y){
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(x[i][j]!=y[i][j])
return 0;
return 1;
}
int d[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
queue<node>q1,q2;
void bfs(){
bool p=1;
q1.push(st);
q2.push(node());
if(st==node()){
cout<<0;
return;
}
while(!q1.empty() && !q2.empty()){
if(p){
node u=q1.front();
q1.pop();
int x,y;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(u[i][j]==0) x=i,y=j;
for(int i=0;i<4;i++){
int tx=x+d[i][0],ty=y+d[i][1];
if(tx<0 || ty<0 || tx>=3 || ty>=3) continue;
node t=u;
swap((int&)t[x][y],(int&)t[tx][ty]);
t.step++;
if(mp[t.to_string()].first==2){
cout<<t.step+mp[t.to_string()].second<<"\n";
return;
}
else if(mp[t.to_string()].first==1) continue;
mp[t.to_string()]={1,t.step};
q1.push(t);
}
p=0;
}
else{
node u=q2.front();
q2.pop();
int x,y;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(u[i][j]==0) x=i,y=j;
for(int i=0;i<4;i++){
int tx=x+d[i][0],ty=y+d[i][1];
if(tx<0 || ty<0 || tx>=3 || ty>=3) continue;
node t=u;
swap((int&)t[x][y],(int&)t[tx][ty]);
t.step++;
if(mp[t.to_string()].first==1){
cout<<t.step+mp[t.to_string()].second<<"\n";
return;
}
else if(mp[t.to_string()].first==2) continue;
mp[t.to_string()]={2,t.step};
q2.push(t);
}
p=1;
}
}
}
int main() {
st.input();
bfs();
return 0;
} 例题:迷宫寻路.
此题普通BFS当然可以过,我们来尝试一下双向BFS。
这题明天再写,毕竟我是一只鸽子。
第六个优化:IDA*
IDA* 就是迭代加深的 A* 算法。
它是用估价函数 来判断在此深度下有没有解。
深搜时,如果 直接 return。
IDA* 在一些情况下比 A* 更实用。
例题:八数码问题.
又是老朋友八数码。
此题也可以用 IDA* 做。
与 A* 相同,估价函数是一样的。
用迭代加深的形式与估价函数判断有没有解。
这题明天再写,毕竟我是一只鸽子。