poj 3221 Diamond Puzzle (BFS)
来源:互联网 发布:数据库归档日志满了 编辑:程序博客网 时间:2024/05/29 04:46
给一个0~6组成的串,用特殊的变换方式,得出"0123456",只有0是空的
用的最原始的BFS,因为只有0~6几个字符,而且总的N<=5040,比较大,所以考虑从终点"0123456"开始搜索,预处理出每个状态的时间,然后O(1)的查询.
图中的数字,对应字符串的下标.
用d[i][j]表示当0处在i处时,它能和d[i][j]相交换!
#include<stdio.h>#include<map>#include<queue>#include<string>#include<string.h>#include<algorithm>using namespace std;struct node{ char s[10]; int t;};map<string,int>m;//用来存字符串状态是否已经被搜过.map<string,int>ans;//用来存每个字符串状态的答案.int n;char s[10];char S[10]="0123456";int d[8][5]={{2,4,6,-1},{2,6,-1},{0,1,3,-1},{2,4,-1},{0,3,5,-1},{4,6,-1},{0,1,5,-1}};void bfs(){ queue<node>q; node vw,vn; strcpy(vn.s,S); vn.t=0; m[S]=1; q.push(vn); while(!q.empty()) { vn=q.front(); q.pop(); ans[vn.s]=vn.t; int tag; for(int i=0;i<7;i++) { if(vn.s[i]=='0') { tag=i;break; } } for(int i=0;d[tag][i]!=-1;i++) { strcpy(vw.s,vn.s); int ti=vn.t; int t=d[tag][i]; char c=vw.s[tag]; vw.s[tag]=vw.s[t]; vw.s[t]=c; string b=vw.s; if(m[b]!=1) { vw.t=ti+1; m[b]=1; q.push(vw); } } }}int main(){ bfs(); scanf("%d",&n); while(n--) { scanf("%s",s); if(strcmp(S,s)==0) printf("0\n"); else printf("%d\n",ans[s]==0?-1:ans[s]); }}
- poj 3221 Diamond Puzzle (BFS)
- poj 3221Diamond Puzzle(bfs+状压)
- POJ 3221 Diamond Puzzle(BFS)
- poj 3221 Diamond Puzzle 反向bfs
- POJ 3221 Diamond Puzzle.
- POJ 3221:Diamond Puzzle(六数码 反向bfs)
- POJ3221 Diamond Puzzle(BFS:最短路)
- POJ 3131 Cubic Eight-Puzzle 双向BFS + HASH
- POJ-3131-Cubic Eight-Puzzle(双向BFS+哈希)
- Dearboy's Puzzle (poj 2308 搜索 dfs+bfs)
- poj 3131 Cubic Eight-Puzzle (双向bfs+深度控制 立体八数码)
- UESTC1490 Eight Puzzle 双向BFS
- BFS ZOJ 3814 Sawtooth Puzzle
- Seven Puzzle (AOJ 0121 bfs)
- USACO 4.4 Shuttle Puzzle bfs
- Aoj 0121 Seven Puzzle【bfs】
- Diamond
- Diamond
- cocos2d-x自己封装的一个 等待的控件 TTWaitting
- Oracle和SQLserver
- POJ 1276 cash machine
- oracle 表空间管理
- 基于Linux的嵌入式系统全程喂狗策略
- poj 3221 Diamond Puzzle (BFS)
- linux下mysql备份数据入门
- 【搜狐笔试】显示所有正确的括号匹配
- MyEclipse+MySql插入中文乱码问题解决
- oracle drop table(表)数据恢复方法
- hdu 2586 How far away ?
- hdu 2586 How far away ?【最近公共祖先】
- hdu 1097 A hard puzzle
- 403 Forbidden怎么解决