bfs路径打印

来源:互联网 发布:经典名著改编电影知乎 编辑:程序博客网 时间:2024/06/04 17:47
#include <iostream>#include <cstring>#include <cstdio>#include <queue>#include <string>#include <map>#include <algorithm>#include <utility>using namespace std;const int dx[4] = {0, 0, -1, 1};const int dy[4] = {1, -1, 0, 0};  const int MAXN = 300000;int tot = 0;struct pii{    int x, y, pre, ord;    pii(){}    pii(int x, int y, int pre, int ord):x(x), y(y), pre(pre), ord(ord){}};struct Node{    int x, y, step, index;    int A[3][3];    Node(){}    Node(Node &rhs, int step, int index){        for(int i=0; i<3; ++i){            for(int j=0; j<3; ++j){                A[i][j] = rhs.A[i][j];                if(A[i][j] == 9){                    x = i;                    y = j;                }            }        }        this->step = step;        this->index = index;    }    string toString(){        string ret = "";        for(int i=0; i<3; ++i){            for(int j=0; j<3; ++j){                ret += (char)(A[i][j] + '0');            }        }        return ret;    }    void change(int x1, int y1){        int temp = A[x1][y1];        A[x1][y1] = A[x][y];        A[x][y] = temp;        x = x1; y = y1;        step += 1;        index = ++tot;    }    bool judge(){        for(int i=0; i<3; ++i){            for(int j=0; j<3; ++j){                if(A[i][j] != i*3 + j + 1) return false;            }        }        return true;    }};Node rhs;pii B[MAXN];inline bool check(int x, int y){    return (0<=x && x<3 && 0<=y && y<3);}void dfs(int index){    if(B[index].pre != -1) dfs(B[index].pre);    cout<<"("<<B[index].x<<", "<<B[index].y<<") "<<B[index].ord<<endl;}void bfs(){    map<string, bool> mp;    queue<Node> q;    q.push(rhs);    mp[rhs.toString()] = true;    B[tot].x = rhs.x;    B[tot].y = rhs.y;    B[tot].pre = -1;    B[tot].ord = 9;    ++tot;    rhs.index = 0;    while(!q.empty()){        Node now = q.front(); q.pop();        if(now.judge()){            cout<<"total steps are: "<<now.step<<endl;            dfs(now.index);            return;        }        for(int i=0; i<4; ++i){            Node tmp = now;            int tx = tmp.x + dx[i];            int ty = tmp.y + dy[i];            if(check(tx, ty)){                tmp.change(tx, ty);                if(mp[tmp.toString()]) continue;                q.push(tmp);                mp[tmp.toString()] = true;                B[tot].x = tx;                B[tot].y = ty;                B[tot].pre = now.index;                B[tot].ord = now.A[tx][ty];                ++tot;            }        }    }}int main(){    rhs.A[0][0] = 5; rhs.A[0][1] = 1; rhs.A[0][2] = 2;    rhs.A[1][0] = 7; rhs.A[1][1] = 8; rhs.A[1][2] = 4;    rhs.A[2][0] = 6; rhs.A[2][1] = 3; rhs.A[2][2] = 9;    rhs.x = 2;     rhs.y = 2;    rhs.step = 0;    rhs.judge();    bfs();    return 0;}