HDU1043BFS 康托展开 八数码
2013-04-11 20:20
417 查看
经典的八数码问题
至于康托展开,百度知道。。。
至于康托展开,百度知道。。。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <queue> using namespace std; int jc[11] = {1,1,2,6,24,120,720,5040,40320,362880}; bool vis[444444]; string path[444444]; int aim; int mx[4] = {0,0,1,-1}; int my[4] = {1,-1,0,0}; char direction[4] = {'l','r','u','d'}; struct State{ int x,y; int s[11]; int state; string path; }; char mp[4][4]; bool in(State a){ if(a.x >= 0 && a.x < 3 && a.y >= 0 && a.y < 3) return true; else return false; } int contor(int s[]){ int sum = 0; for(int i = 0 ; i < 9 ; i ++){ int num = 0; for(int j = i + 1 ; j < 9 ; j ++){ if(s[j] < s[i]){ num++; } } sum += num*jc[9-i-1]; } return sum + 1; } queue<State> q; void BFS(){ memset(vis,0,sizeof(vis)); State s; for(int i = 0 ; i < 8 ; i ++){ s.s[i] = i+1; } s.s[8] = 0; s.state = contor(s.s); s.x = 2; s.y = 2; s.path = ""; path[s.state] = ""; vis[s.state] = 1; q.push(s); while(!q.empty()){ State cnt = q.front(); q.pop(); for(int i = 0 ; i < 4 ; i ++){ State nt = cnt; nt.x = cnt.x + mx[i]; nt.y = cnt.y + my[i]; if(in(nt) == 0) continue; nt.s[cnt.x*3+cnt.y] = nt.s[nt.x*3+nt.y]; nt.s[nt.x*3+nt.y] = 0; nt.state = contor(nt.s); if(vis[nt.state] == 0){ path[nt.state] = direction[i]+nt.path; nt.path = path[nt.state]; vis[nt.state] = 1; q.push(nt); } } } } int main() { char str; State now; BFS(); while(cin>>str){ if(str == 'x'){ now.x = 0; now.y = 0; now.s[0] = 0; } else now.s[0] = str - '0'; for(int i = 1 ; i < 9 ; i ++){ cin>>str; if(str == 'x'){ now.x = i/3; now.y = i%3; now.s[i] = 0; } else now.s[i] = str-'0'; } now.state = contor(now.s); if(vis[now.state] == 1) cout<<path[now.state]<<endl; else cout<<"unsolvable"<<endl; } return 0; }
相关文章推荐
- POJ 1077 八数码(康托展开+暴力bfs)
- hdu1043Eight (经典的八数码)(康托展开+BFS)
- HDU 1043 Eight (BFS·八数码·康托展开)
- HDU 1043 Eight (BFS·八数码·康托展开)
- hdu1043Eight (经典的八数码)(康托展开+BFS)
- HDU1043 Eight(八数码:逆向BFS打表+康托展开)题解
- hdu1043Eight (经典的八数码)(康托展开+BFS)
- 八数码问题的初次解决(康托展开+bfs)
- hdu1043 经典的八数码问题 逆向bfs打表 + 逆序数
- POJ1077 HDU1043 Eight 八数码 (A*+康托展开)
- POJ - 1077 Eight : 八数码 -- 哈唏 康托展开 双向bfs A* IDA*
- ACM之八数码问题----BFS搜索----数独游戏的模拟(中)
- hdu1043(八数码问题,广搜 + hash(实现状态压缩) )
- 【转载】八数码问题BFS与DFS的比较
- 2017ACM-ICPC南宁网络赛Frequent Subsets Problem(康托展开+bfs)
- 八数码问题(A*&&双向BFS)
- POJ1077&&HDU1043(八数码,IDA*+曼哈顿距离)
- hdu1043 bfs 康拓展开
- ACM之八数码问题----BFS搜索----数独游戏的模拟(下)
- BFS:八数码问题