UVA - 1601(双向BFS)

使用双向BFS最大的优点在于 是的结点扩展由 a^(x)变为2*a^(x/2),降低了时间复杂度;

适用于(起始状态和末尾状态都已知);

方法从两端交替逐层搜索(为了保证最短路经优先被找到)


这里借用别人的对错误的搜索方式的解释

如果目标也已知的话,用双向BFS能很大提高速度

单向时,是 b^len的扩展。

双向的话,2*b^(len/2)  快了很多,特别是分支因子b较大时

至于实现上,网上有些做法是用两个队列,交替节点搜索 ×,如下面的伪代码:
    while(!empty()){

            扩展正向一个节点

           遇到反向已经扩展的return

        扩展反向一个节点      

            遇到正向已经扩展的return      

      }

但这种做法是有问题的,如下面的图:


求S-T的最短路,交替节点搜索(一次正向节点,一次反向节点)时

Step 1 : S –> 1 , 2

Step 2 : T –> 3 , 4

Step 3 : 1 –> 5

Step 4 : 3 –> 5   返回最短路为4,错误的,事实是3,S-2-4-T


uva - 1601 (双搜的试验田)


#include
#include
#include
#include
#include 
using namespace std;
#define rep(i,n) for(int i=0;i<=n;i++)
const int N    = 17;
const int maxn = 200;
const int dx[] = {1,0,-1,0,0};
const int dy[] = {0,-1,0,1,0};
int n,m,k;
char maze[N][N];
int x[maxn],y[maxn],cnt,G[maxn][5],deg[maxn],id[maxn][maxn];
//dig out all of the space position so that each position can be replace by an ID number;
int s[3],t[3];
int d[maxn][maxn][maxn],bd[maxn][maxn][maxn];

int ID(int a,int b,int c)
{
    return (a<<16)|(b<<8)|c;
}
void Memset(){
    rep(i,cnt)rep(j,cnt)rep(k,cnt) {
        d[i][j][k]=-1; bd[i][j][k]=-1;
    }
}
bool conflict(int a,int b,int na,int nb)
{
    if(a==nb&&b==na) return true;
    if(na==nb) return true;
    return false;
}
queue q;
bool bfs()
{
    int value;
    int uu=q.front();
    int aa=(uu>>16)&0xff,bb=(uu>>8)&0xff,cc=uu&0xff;
    value=d[aa][bb][cc];
    //cout<<"front"<<"-->"<>16)&0xff,b=(u>>8)&0xff,c=u&0xff;
        if(d[a][b][c]!=value) return false;
        if(bd[a][b][c]!=-1) return true;
        //if(a==t[0]&&b==t[1]&&c==t[2]) return d[a][b][c];
        for(int i=0; i p;
int back_bfs(){
    int value;
    int uu=p.front();
    int aa=(uu>>16)&0xff,bb=(uu>>8)&0xff,cc=uu&0xff;
    value=bd[aa][bb][cc];
    //cout<<"back"<<"-->"<>16)&0xff,b=(u>>8)&0xff,c=u&0xff;
        if(bd[a][b][c]!=value) return false;
        if(d[a][b][c]!=-1) return true;
        //if(a==t[0]&&b==t[1]&&c==t[2]) return d[a][b][c];
        for(int i=0; i"<



你可能感兴趣的:(暴力搜索)