八数码问题,初始局面和目标局面最少移动步数

八数码问题可以通过转化为图的最短路问题来解决,使用广度优先搜索(BFS)进行求解。文中提到三种盘秤方法,重点介绍了使用哈希技术的解法,强调哈希函数在提高效率中的关键作用。样例输入和输出展示了具体问题的解决步骤,输出步数为31。
摘要由CSDN通过智能技术生成

分析:不难吧八数码问题归结为图上的最短路问题,图的“结点”就是9个格子中的编号(从上到下,从左到右把他们放到一个包含9个元素的数组中)。

然后。无权图上的最短路问题可以用bfs求解,代码如下:



#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef int State[9];
const int maxstate = 1000000;
State st[maxstate],goal;
int dist[maxstate];
const int hashsize = 1000003;
int head[hashsize],next[maxstate];
const int dx[]={-1,1,0,0};
const int dy[]={0,0,-1,1};
void init_lookup_table()
{
memset(head,0,sizeof(head));
}
int hash(State &s)
{
int i,v=0;
for(i=0;i<9;i++)
v=v*10+s[i];
return v%hashsize;
}

int try_to_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=next[u];
}
next[s]=head[h];
head[h]=s;
return 1;
}
int bfs()
{
<span style="color:#ff0000;">init_lookup_table();</span>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值