http://codevs.cn/problem/1225/
题目描述 Description
Yours和zero在研究A*启发式算法.拿到一道经典的A*问题,但是他们不会做,请你帮他们.
问题描述
在3×3的棋盘上,摆有八个棋子,每个棋子上标有1至8的某一数字。棋盘中留有一个空格,空格用0来表示。空格周围的棋子可以移到空格中。要求解的问题是:给出一种初始布局(初始状态)和目标布局(为了使题目简单,设目标状态为123804765),找到一种最少步骤的移动方法,实现从初始布局到目标布局的转变。
输入描述 Input Description
输入初试状态,一行九个数字,空格用0表示
输出描述 Output Description
只有一行,该行只有一个数字,表示从初始状态到目标状态需要的最少移动次数(测试数据中无特殊无法到达目标状态数据)
样例输入 Sample Input
283104765
样例输出 Sample Output
4
数据范围及提示 Data Size & Hint
详见试题
本题解大部分引用了刘汝佳《算法入门经典》(大神倾情巨制,强烈推荐)
#include <iostream>
#include <cstdio>
#include <cstring>
#include <set>
using namespace std;
typedef int State[9];//定义类型 State 就是一个int数组,大小为9
const int maxstate=1000000;
State st[maxstate],goal={1,2,3,8,0,4,7,6,5};//这个是目标
int dist[maxstate];
const int dx[]={-1,1,0,0};
const int dy[]={0,0,-1,1};
set<int>vis;
void init_look_up_table()
{
vis.clear();
}
int try_to_insert( int s)//《算法入门经典》中列举了三种方法,这是最简单的的一种。就是把数组一次表示成9位数进行hash检索
{
int v=0;
for(int i=0;i<=9;i++)v=v*10+st[s][i];
if(vis.count(v))return 0;
vis.insert(v);
return 1;
}
int bfs()
{
init_look_up_table();
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;z++)if(s[z]==0)break;//对于此类题(相似的还有华容道)移动某一数字就相当于移动空格,所以先找到空格
int x=z/3,y=z%3;//空格所在位置转换成3*3的平面图(x,y)
for(int d=0;d<4;d++)
{
int newx=x+dx[d];
int newy=y+dy[d];
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(try_to_insert(rear))rear++;
}
}
front++;
}
return 0;
}
int main()
{
string str;
cin>>str;
for(int i=0;i<9;i++)st[1][i]=str[i]-'0';
int ans=bfs();
if(ans>0)printf("%d",dist[ans]);
return 0;
}
#include<cstdio>
#include<cstring>
#include<set>
using namespace std;
typedef int State[9];
const int MAXSTATE = 1000000;
State st[MAXSTATE], goal;
int dist[MAXSTATE];
const int MAXHASHSIZE = 1000003;
int head[MAXHASHSIZE], next[MAXSTATE];
void init_lookup_table() { memset(head, 0, sizeof(head)); }
int hash(State& s) {
int v = 0;
for(int i = 0; i < 9; i++) v = v * 10 + s[i];
return v % MAXHASHSIZE;
}
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 vis[362880], fact[9];
void init_lookup_table() {
fact[0] = 1;
for(int i = 1; i < 9; i++) fact[i] = fact[i-1] * i;
}
int try_to_insert(int s) {
int code = 0;
for(int i = 0; i < 9; i++) {
int cnt = 0;
for(int j = i+1; j < 9; j++) if(st[s][j] < st[s][i]) cnt++;
code += fact[8-i] * cnt;
}
if(vis[code]) return 0;
return vis[code] = 1;
}