1. 程式人生 > >雙向廣度優先搜尋演算法框架

雙向廣度優先搜尋演算法框架

雙向廣度優先搜尋演算法是對廣度優先演算法的一種擴充套件。廣度優先演算法從起始節點以廣度優先的順序不斷擴充套件,直到遇到目的節點;而雙向廣度優先演算法從兩個方向以廣度優先的順序同時擴充套件,一個是從起始節點開始擴充套件,另一個是從目的節點擴充套件,直到一個擴充套件佇列中出現另外一個佇列中已經擴充套件的節點,也就相當於兩個擴充套件方向出現了交點,那麼可以認為我們找到了一條路徑。雙向廣度優先演算法相對於廣度優先演算法來說,由於採用了從兩個跟開始擴充套件的方式,搜尋樹的深度得到了明顯的減少,所以在演算法的時間複雜度和空間複雜度上都有較大的優勢!雙向廣度優先演算法特別適合於給出了起始節點和目的節點,要求他們之間的最短路徑的問題。另外需要說明的是,廣度優先的順序能夠保證

找到的路徑就是最短路徑!

基於以上思想,我們給出雙向廣度優先演算法程式設計的基本框架如下:

資料結構:

Queue q1, q2; //兩個佇列分別用於兩個方向的擴充套件(注意在一般的廣度優先演算法中,只需要一個佇列)

int head[2], tail[2]; //兩個佇列的頭指標和尾指標

演算法流程:

一、主控函式:

void solve()

{

1. 將起始節點放入佇列q1,將目的節點放入佇列q2

2. 當 兩個佇列都未空時,作如下迴圈

          1) 如果佇列q1裡的未處理節點比q2中的少(即tail[0]-head[0] < tail[1]-head[1]),則擴充套件(expand())

佇列q1

          2) 否則擴充套件(expand())佇列q2 (即tail[0]-head[0] >= tail[1]-head[1]時)

3. 如果佇列q1未空,迴圈擴充套件(expand())q1直到為空

4. 如果佇列q2未空,迴圈擴充套件(expand())q2知道為空

}

二、擴充套件函式:

int expand(i) //其中i為佇列的編號(表示q0或者q1)

{

          取佇列qi的頭結點H

          對頭節點H的每一個相鄰節點adj,作如下迴圈

                1 如果adj已經在佇列qi之前的某個位置出現,則拋棄節點adj

                2 如果adj在佇列qi中不存在[函式 isduplicate(i)]

                      1) 將adj放入佇列qi

                      2)    如果adj 在佇列(q(1-i)),也就是另外一個佇列中出現[函式 isintersect()]

                                      輸出 找到路徑 

}

三、判斷新節點是否在同一個佇列中重複的函式

int isduplicate(i, j) //i為佇列編號,j為當前節點在佇列中的指標

{

            遍歷佇列,判斷是否存在【線性遍歷的時間複雜度為O(N),如果用HashTable優化,時間複雜度可以降到O(1)]

}

四、判斷當前擴展出的節點是否在另外一個隊列出現,也就是判斷相交的函式:

int isintersect(i,j) //i為佇列編號,j為當前節點在佇列中的指標

{

          遍歷佇列,判斷是否存在【線性遍歷的時間複雜度為O(N),如果用HashTable優化,時間複雜度可以降到O(1)]

}

      以上為雙向廣度優先搜尋演算法的基本思路,下面給出使用上面的演算法框架編寫的八數碼問題的程式碼:

問題描述:

給定 3 X 3 的矩陣如下:
2     3     4

1     5      x

7     6     8

程式每次可以交換"x"和它上下左右的數字,

經過多次移動後得到如下狀態:

1      2     3

4      5     6

7      8      x

輸出在最少移動步數的情況下的移動路徑[每次移動的方向上下左右依次表示為'u', 'd', 'l', 'r']

例如:

如果過輸入:【將矩陣放到一行輸出】

 2  3  4 1  5  x  7  6  8

則輸出:

ullddrurdllurdruldr

原題見ACM PKU 1077

‍C++程式碼如下:【注意,這是沒有使用HASH優化的版本,壓線通過了ACM PKU線上測試的記憶體和時間要求】

/*
 * Author: puresky
 * Date: 2010.01.12
 * Purpose: solve EIGTH NUMBER problem!
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXN 1000000

#define SWAP(a, b) {char t = a; a = b; b = t;}

typedef struct _Node Node;

struct _Node
{
        char tile[10]; // represent the tile as a string ending with '\0'
        char pos;   // the position of 'x'
        char dir;  //the moving direction of 'x'
        int parent; //index of parent node
};

int head[2], tail[2];
Node queue[2][MAXN];// two queues for double directoin BFS

//shift of moving up, down, left ,right
int shift[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

//for output direction!
char dir[4][2] = {{'u', 'd'}, {'d', 'u'}, {'l', 'r'}, {'r', 'l'}};

//test case
char start[10] = "23415x768";
char end[10] = "12345678x";

//read a tile 3 by 3
void readtile()
{
        int i;
        char temp[10];
        for(i = 0; i < 9; ++i)
        {
                scanf("%s", temp);
                start[i] = temp[0];
        }
        start[9] = '\0';
}

//print result
void print_backward(int i)
{
        if(queue[0][i].parent != -1)
        {
                print_backward(queue[0][i].parent);
                printf("%c", queue[0][i].dir);
        }
}
void print_forward(int j)
{
        if(queue[1][j].parent != -1)
        {
                printf("%c", queue[1][j].dir);
                print_forward(queue[1][j].parent);
        }
}
void print_result(int i, int j)
{
        //printf("%d,%d\n", i, j);
        print_backward(i);
        print_forward(j);
        printf("\n");
}

//init the queue
void init(int qi, const char* state)
{
        strcpy(queue[qi][0].tile, state);
        queue[qi][0].pos = strchr(state, 'x') - state;
        queue[qi][0].parent = -1;

        head[qi] = tail[qi]  = 0;
}

//check if there are duplicates in the queue
//time comlexity:O(n)
//We can optimise this function using HashTable
int isduplicate(int qi)
{
        int i;
        for(i = 0; i < tail[qi]; ++i)
        {
                if(strcmp(queue[qi][tail[qi]].tile, queue[qi][i].tile) == 0)
                {
                        return 1;
                }
        }
        return 0;
}

//check if the current node is in another queue!
//time comlexity:O(n)
//We can optimise this function using HashTable
int isintersect(int qi)
{
        int i;
        for(i = 0 ; i < tail[1 - qi]; ++i)
        {
                if(strcmp(queue[qi][tail[qi]].tile, queue[1 - qi][i].tile) == 0)
                {
                        return i;
                }
        }

        return -1;
}

//expand nodes
int expand(int qi)
{
        int i, x, y, r;

        Node* p = &(queue[qi][head[qi]]);
        head[qi]++;

        for(i = 0; i < 4; ++i)
        {
                x = p->pos / 3 + shift[i][0];
                y = p->pos % 3 + shift[i][1];
                if(x >= 0 && x <= 2 && y >= 0 && y <= 2)
                {
                        tail[qi]++;
                        Node* pNew = &(queue[qi][tail[qi]]);
                        strcpy(pNew->tile, p->tile);
                        SWAP(pNew->tile[ 3 * x + y], pNew->tile[p->pos]);
                        pNew->pos = 3 * x + y;
                        pNew->parent = head[qi] - 1;
                        pNew->dir = dir[i][qi];
                        if(isduplicate(qi))
                        {
                                tail[qi]--;
                        }
                        else
                        {
                                if((r = isintersect(qi)) != -1)
                                {
                                        if(qi == 1)
                                        {
                                                print_result(r, tail[qi]);
                                        }
                                        else
                                        {
                                                print_result(tail[qi], r);
                                        }
                                        return 1;
                                }
                        }
                }
        }
        return 0;
}

//call expand to generate queues
int solve()
{
        init(0, start);
        init(1, end);

        while(head[0] <= tail[0] && head[1] <= tail[1])
        {
                //expand the shorter queue firstly
                if(tail[0] - head[0] >= tail[1] - head[1])
                {
                        if(expand(1)) return 1;
                }
                else
                {
                        if(expand(0)) return 1;
                }
        }

        while(head[0] <= tail[0]) if(expand(0)) return 1;
        while(head[1] <= tail[1]) if(expand(1)) return 1;
        return 0;
}

int main(int argc, char** argv)
{
        readtile();
        if(!solve())
        {
                printf("unsolvable\n");
        }
        //system("pause"); //pause
        return 0;
}

ACM Judge Online: 372K 記憶體, 938MS 時間

以上內容為轉載。接下來附上我參考該轉載文章寫的POJ1077雙向廣搜程式碼:

<span style="color:#ff0000;">Source Code

Problem: 1077		User: liangrx06
Memory: 15316K		Time: 141MS
Language: C++		Result: Accepted
Source Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;

typedef int State[9];
const int M = 1000000;
State st[M], goal;
//int dist[M];
int pre[M];
char move[M];

const int HASH_SIZE = M+3;
int head[HASH_SIZE], next[HASH_SIZE];

void init_lookup_table()
{
    memset(head, 0, sizeof(head));
    memset(next, 0, sizeof(next));
}

bool legal(int x, int y)
{
    return 0 <= x && x < 3 && 0 <= y && y < 3;
}

int hash(State& s)
{
    int t = 0;
    for (int i = 0; i < 9; i++) t = t * 10 + s[i];
    return t % HASH_SIZE;
}

bool try_to_insert(int k)
{
    int h = hash(st[k]);
    int u = head[h];
    while (u) {
        if (memcmp(st[u], st[k], sizeof(st[k])) == 0) return false;
        u = next[u];
    }
    next[k] = head[h];
    head[h] = k;
    return true;
}

const int dir[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
const char move_type[] = "drul";
int BFS()
{
    init_lookup_table();

    int front = 1, rear = 2;
    while (front < rear) {
        State& s = st[front];
        if (memcmp(goal, s, sizeof(s)) == 0)
            return front;
        int z;
        for (z = 0; z < 9; z++) if (!s[z]) break;
        int x = z/3, y = z%3;
        for (int i = 0; i < 4; i++) {
            int nx = x + dir[i][0];
            int ny = y + dir[i][1];
            if (legal(nx, ny)) {
                int nz = nx*3 + ny;
                State& t = st[rear];
                memcpy(t, s, sizeof(s));
                swap(t[z], t[nz]);
                if (try_to_insert(rear)) {
                    //dist[rear] = dist[front] + 1;
                    pre[rear] = front;
                    move[rear] = move_type[i];
                    rear++;
                }
            }
        }
        front ++;
    }
    return 0;
}
        
int main(void)
{   
    char str[2];
    for (int i = 0; i < 9; i++) {
        scanf("%s", str);
        st[1][i] = (str[0] == 'x') ? 0 : str[0]-'0';
        goal[i] = (i+1)%9; 
    } 
    //dist[1] = 0;

    int step = BFS();
    vector<char> res;
    while (step != 1) { 
        res.push_back(move[step]);
        step = pre[step];
    }   
    for (int i = res.size()-1; i >= 0; i--)
        printf("%c", res[i]);
    printf("\n");
        
    return 0;
}</span>