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;}
阅读全文
0 0
- BFS(简单路径打印)
- bfs路径打印
- bfs--hdoj1026(打印路径)
- hdu1026(BFS,打印路径)
- bfs广搜:打印路径
- POJ 3984 BFS 打印路径
- 迷宫问题bfs+打印路径
- remainder(bfs路径打印)
- bfs迷宫问题--打印路径
- POJ 3414 Pots ( BFS , 打印路径 )
- 广度优先搜索(BFS)+路径打印
- POJ -3414 Pots(BFS + 打印路径)
- POJ 3414 Pots (BFS+路径打印)
- BFS和DFS路径存储和打印
- poj3414——bfs+路径打印
- 关于 BFS 中 打印路径的问题
- poj3984 迷宫问题 简单bfs打印路径
- hdu1026(bfs+dfs打印路径)
- mybatis执行insert实体后返回主键
- MyBatis01
- git tag 标签完全用法(如何更好的管理你的分支)
- LBaas之(六)python-neutronclient架构分析
- SpringBoot开发详解(九) -- 使用JPA访问数据库上篇
- bfs路径打印
- Linux里如何查找文件内容
- 由@suppressWarnings("unchecked")想到的一丢丢
- struts
- python文本读写,with open as
- Ubuntu Server 16.04中文方块菱形乱码问题解决
- myBatis02
- 在YOLO2中增加自己的物体识别(二)
- hdu Problem-1584蜘蛛牌dfs