八数码问题和bfs中的判重方法
2012-08-01 17:31
337 查看
所谓八数码问题就是有一个编号为1~8的正方形滑块被摆成3行3列(留一个格子空着)每次可以把与空格相邻的滑块(有公共边的才算相邻)移动到空格中,而它原来的位置就成为了新的空格,给定初始的局面和目标局面,你的任务就是计算出最少的移动步数,如果无法达到目标局面,就输出-1.
AC代码:
AC代码:
#include<cstdio> #include<string.h> #include<stdlib.h> #include<string> #include<algorithm> #define N 1000000 #define M 1000003 using namespace std; typedef int State[9]; State st ,goal; int dist ; int dx[]={-1,1,0,0}; int dy[]={0,0,-1,1}; int head ,nex ; int Hash(State& s) { int v=0; for(int i=0;i<9;++i) v=v*10+s[i]; return v%M; } int _insert(int s) { int h=Hash(st[s]); int u=head[h]; while(u)//判断该状态是否已经存在 { if(memcmp(st[u],st[s],sizeof(st[s]))==0) return 0; u=nex[u]; } nex[s]=head[h];//插入到链表中 head[h]=s; return 1; } int bfs() { memset(head,0,sizeof(head)); memset(dist,0,sizeof(dist)); int front=1,rear=2; while(front<rear) { State& s=st[front];//用引用简化代码 if(memcmp(goal,s,sizeof(s))==0) return front;//找到目标状态,返回 int z; for(z=0;z<9&&s[z];z++);//找到0的位置 int x=z/3; int y=z%3;//获取0的行列编号 for(int i=0;i!=4;++i) { int newx=x+dx[i]; int newy=y+dy[i]; int newz=newx*3+newy; if(newx>=0&&newx<3&&newy>=0&&newy<3) { State& t=st[rear]; memcpy(&t,&s,sizeof(s));//扩展新节点 t[newz]=s[z]; t[z]=s[newz]; dist[rear]=dist[front]+1;//更新新节点的距离 if(_insert(rear)) rear++;//如果成功插入,则修改队尾指针 } } front++;//扩展完毕修改队首指针 }return -1; } int main() { int T; scanf("%d",&T); while(T--) { for(int i=0;i!=9;++i) scanf("%d",&st[1][i]); for(int i=0;i!=9;++i) scanf("%d",&goal[i]); int ans=bfs(); printf("%d\n",(ans==-1)?-1:dist[ans]); }return 0; } /* 2 6 4 1 3 7 0 5 8 8 1 5 7 3 6 4 0 2 31 */
相关文章推荐
- 八数码问题和bfs中的判重方法
- 【BFS】由八数码问题的BFS解法引出的三种BFS经典状态判重方法
- NPU17届程序设计 1571 八数码问题 暴力BFS
- 八数码问题的初次解决(康托展开+bfs)
- 简单的八数码问题(BFS)
- 多种方法求解八数码问题
- BFS 八数码问题 typedef int State[9]; (BFS A*算法与优先队列)
- 由八数码问题引入。对BFS有更深考虑
- 图算法_普通广度优先搜索(BFS)解八数码问题_C语言
- 八数码问题(A*&&双向BFS)
- 单向搜索bfs,PKU1077,八数码问题
- poj 1077 Eight 八数码问题( 康拓展开+BFS状态压缩)
- BFS 八数码问题 typedef int State[9]; (BFS A*算法与优先队列)
- BFS和DFS方法解决走迷宫问题
- 关于八数码问题中的状态判重的三种解决方法(编码、hash、<set>)
- 多种方法求解八数码问题
- 每天刷个算法题20160526:BFS解决八数码问题(九宫格问题)
- 多种方法求解八数码问题
- ACM之八数码问题----BFS搜索----数独游戏的模拟(下)
- BFS 八数码问题 typedef int State[9]; (BFS A*算法与优先队列)