bfs路径打印
2017-05-30 22:02
169 查看
#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; }
相关文章推荐
- Codeforces 3A-Shortest path of the king(BFS打印路径)
- remainder(bfs路径打印)
- h1026 BFS(打印x与路径)
- 最大流最小割算法; BFS搜索增广路径; 算法简单,打印结果也比较清晰;
- 关于 BFS 中 打印路径的问题
- bfs 较为全面的迷宫路径问题,包括路径的打印,起点到任一点的最小步数.
- HDU 1026 Ignatius and the Princess I BFS打印路径
- HDU 1104 Remainder(BFS打印路径+数论)(%与mod的区别)
- 迷宫BFS+递归回溯找爹打印路径
- 用BFS找最短路,并打印路径
- BFS(简单路径打印)
- POJ3984 BFS打印路径
- BFS(最短路+路径打印) POJ 3984 迷宫问题
- POJ ~ 3414 ~ Pots (BFS+打印路径)
- bfs广搜:打印路径
- POJ ~ 3984 ~ 迷宫问题 (BFS+打印路径)
- TOJ---3128---bfs(打印路径)
- poj3984 迷宫问题 简单bfs打印路径
- 迷宫问题:利用BFS打印出从起点到终点的路径(java版)
- bfs打印最短路径