Eight
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 43117 Accepted: 17541 Special Judge
Description
The 15-puzzle has been around for over 100 years; even if you don’t know it by that name, you’ve seen it. It is constructed with 15 sliding tiles, each with a number from 1 to 15 on it, and all packed into a 4 by 4 frame with one tile missing. Let’s call the missing tile ‘x’; the object of the puzzle is to arrange the tiles so that they are ordered as:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 x
where the only legal operation is to exchange ‘x’ with one of the tiles with which it shares an edge. As an example, the following sequence of moves solves a slightly scrambled puzzle:
The letters in the previous row indicate which neighbor of the ‘x’ tile is swapped with the ‘x’ tile at each step; legal values are ‘r’,‘l’,‘u’ and ‘d’, for right, left, up, and down, respectively.
Not all puzzles can be solved; in 1870, a man named Sam Loyd was famous for distributing an unsolvable version of the puzzle, and
frustrating many people. In fact, all you have to do to make a regular puzzle into an unsolvable one is to swap two tiles (not counting the missing ‘x’ tile, of course).
In this problem, you will write a program for solving the less well-known 8-puzzle, composed of tiles on a three by three
arrangement.
Input
You will receive a description of a configuration of the 8 puzzle. The description is just a list of the tiles in their initial positions, with the rows listed from top to bottom, and the tiles listed from left to right within a row, where the tiles are represented by numbers 1 to 8, plus ‘x’. For example, this puzzle
1 2 3
x 4 6
7 5 8
is described by this list:
1 2 3 x 4 6 7 5 8
Output
You will print to standard output either the word ``unsolvable’’, if the puzzle has no solution, or a string consisting entirely of the letters ‘r’, ‘l’, ‘u’ and ‘d’ that describes a series of moves that produce a solution. The string should include no spaces and start at the beginning of the line.
Sample Input
2 3 4 1 5 x 7 6 8
Sample Output
ullddrurdllurdruldr
题意:
给定一个八数码序列,要求移动x,使得序列变成12345678x,问所需要的操作过程。
代码
下面这段是我自己写的代码,在c++里面TLE了,只能在g++里面通过。
#include<iostream>
#include<queue>
#include<cstring>
#include<ctime>
#include<cstdio>
using namespace std;
const int n=9;
const int N=362880;
const int aim = 46233;//结束状态的康托值
int start[n];
int goal[n]={1,2,3,4,5,6,7,8,0};
int factory[]={1,1,2,6,24,120,720,5040,40320,362880};
int vis[N]={0};
int parent[N];//记录状态N的上一个状态
char step[N];//记录状态N的操作
const char direct[4] = { 'u','d','l','r' };
const int dir[4][2] = { {-1,0},{1,0},{0,-1},{0,1} };
struct node{
int state[n];
int hash;
};
int cantor(int s[])
{
int result=0;
for(int i=0;i<n;i++){
int cnt=0;
for(int j=i+1;j<n;j++){
if(s[i]>s[j]) cnt++;
}
result+=cnt*factory[n-i-1];
}
return result;
}
void printPath() {
char queue[N];
int t = 0;
int c = aim;
while (parent[c] != -1) {
queue[t] = step[c];
++t;
c = parent[c];
}
for (int i = t - 1; i >= 0; --i)printf("%c", queue[i]);
printf("\n");
}
void bfs()
{
queue<node> Q;
node head;
memset(vis, 0, sizeof(vis));
memcpy(head.state,start,sizeof(head.state));
head.hash=cantor(head.state);
vis[head.hash]=1;
parent[head.hash]=-1;
Q.push(head);
while(!Q.empty()){
head=Q.front();
Q.pop();
int z;
for(z=0;z<n;z++)
if(head.state[z]==0) break;
int x,y;
x=z/3;y=z%3;
for(int i=0;i<4;i++){
int newx,newy;
newx=x+dir[i][0];
newy=y+dir[i][1];
int nz=newx*3+newy;
if(newx>=0&&newx<3&&newy>=0&&newy<3){
node newnode;
memcpy(&newnode,&head,sizeof(struct node));
swap(newnode.state[z],newnode.state[nz]);//交换0的位置
newnode.hash=cantor(newnode.state);//算出新状态的康托值
if(!vis[newnode.hash]){
parent[newnode.hash]=head.hash;
step[newnode.hash]=direct[i];
vis[newnode.hash]=1;
if (newnode.hash == aim) return;
Q.push(newnode);
}
}
}
}
}
int main() {
char x;
// freopen("data.txt","r",stdin);
for (int i = 0; i < n; ++i) {
scanf(" %c", &x);
if (x == 'x') start[i] = 0;
else start[i] = x - '0';
}
// clock_t star,end;
// star=clock();
bfs();
// end=clock();
// cout<<(double)(end-star)/CLOCKS_PER_SEC<<endl;
if (!vis[aim])printf("unsolvable\n");
else printPath();
return 0;
}
下面是网上看到的一段代码,里面用到了康托展开和逆展开,写的很不错,这段可以在c++里面通过。
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<ctime>
using namespace std;
const char direct[4] = { 'u','d','l','r' };
const int dir[4][2] = { {-1,0},{1,0},{0,-1},{0,1} }, N = 362880;
const int aim = 46233;
const int n = 9;
bool visit[N];
char step[N];
int parent[N];
//阶乘
const int fac[n] = { 1,1,2,6,24,120,720,5040,40320 };
//康托展开
int cantor(int s[]) {
int result = 0, cnt = 0;
for (int i = 0; i < n - 1; ++i) {
cnt = 0;
for (int j = i + 1; j < n; ++j) {
if (s[i] > s[j])++cnt;
}
result += fac[n - 1 - i] * cnt;
}
return result;
}
//逆康托展开,s[]里面存的是reverse后的原值,space存的是0的位置
void reverseCantor(int hash, int s[], int &space) {
bool visited[n] = {};
int temp;
for (int i = 0; i < n; ++i) {
temp = hash / fac[n - 1 - i];
for (int j = 0; j < n; ++j) {
if (!visited[j]) {
if (temp == 0) {
s[i] = j;
if (j == 0)space = i;
visited[j] = true;
break;
}
--temp;
}
}
hash %= fac[8 - i];
}
}
void bfs(int start) {
queue<int> q;
q.push(start);
visit[start] = true;
parent[start] = -1;
int state[n], space;
while (!q.empty()) {
int preHash = q.front();
q.pop();
//康托逆展开,根据hash值得出状态state和0的位置space
reverseCantor(preHash, state, space);
for (int i = 0; i < 4; ++i) {
int tx = space / 3 + dir[i][0];
int ty = space % 3 + dir[i][1];
if (tx < 0 || tx>2 || ty < 0 || ty>2)continue;
int tz = tx * 3 + ty;
//交换0的位置
state[space] = state[tz];
state[tz] = 0;
//算出新的康托值
int hash = cantor(state);
if (!visit[hash]) {
visit[hash] = true;
parent[hash] = preHash;
step[hash] = direct[i];
if (hash == aim)return;
q.push(hash);
}
//0的位置换回来
state[tz] = state[space];
state[space] = 0;
}
}
}
void printPath() {
char queue[N];
int t = 0;
int c = aim;
while (parent[c] != -1) {
queue[t] = step[c];
++t;
c = parent[c];
}
for (int i = t - 1; i >= 0; --i)printf("%c", queue[i]);
printf("\n");
}
int main() {
char x;
int a[n];
// freopen("data.txt","r",stdin);
for (int i = 0; i < n; ++i) {
scanf(" %c", &x);
if (x == 'x')a[i] = 0;
else a[i] = x - '0';
}
int hash = cantor(a);
// clock_t star,end;
// star=clock();
bfs(hash);
// end=clock();
// cout<<(double)(end-star)/CLOCKS_PER_SEC<<endl;
if (!visit[aim])printf("unsolvable\n");
else printPath();
return 0;
}
更多
下面这个大佬的博客还有 A * 算法和 IDA * 算法去实现的代码。
poj1077
A * 算法
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<cmath>
using namespace std;
const char direct[4] = { 'u','d','l','r' };
const int dir[4][2] = { {-1,0},{1,0},{0,-1},{0,1} }, N = 362880;
const int aim = 46233;
const int n = 9;
bool visit[N];
int parent[N];
char step[N];
int goal_state[9][2] = {
{0, 0}, {0, 1}, {0, 2},
{1, 0}, {1, 1}, {1, 2},
{2, 0}, {2, 1}, {2, 2}
};
//阶乘
const int fac[n] = { 1,1,2,6,24,120,720,5040,40320 };
//康托展开
int cantor(int s[]) {
int result = 0, cnt = 0;
for (int i = 0; i < n - 1; ++i) {
cnt = 0;
for (int j = i + 1; j < n; ++j) {
if (s[i] > s[j])++cnt;
}
result += fac[n - 1 - i] * cnt;
}
return result;
}
//逆康托展开
void reverseCantor(int hash, int s[], int &space) {
bool visited[n] = {};
int temp;
for (int i = 0; i < n; ++i) {
temp = hash / fac[n - 1 - i];
for (int j = 0; j < n; ++j) {
if (!visited[j]) {
if (temp == 0) {
s[i] = j;
if (j == 0)space = i;
visited[j] = true;
break;
}
--temp;
}
}
hash %= fac[8 - i];
}
}
//f=g+h —— 评估函数公式
int g[N];
//函数h用来求曼哈顿距离之和
int h(int s[]) {
int k, result = 0;
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
k = i * 3 + j;
if (s[k] == 0)continue;
result += abs(1.0*(i - goal_state[s[k] - 1][0])) + abs(1.0*(j - goal_state[s[k] - 1][1]));
}
}
return result;
}
void printPath() {
char queue[31];
int t = 0;
int c = aim;
while (parent[c] != -1) {
queue[t] = step[c];
++t;
c = parent[c];
}
for (int i = t - 1; i >= 0; --i)printf("%c", queue[i]);
printf("\n");
}
class Chess {
public:
int hash, f;
Chess(const int &hash, const int &f) :hash(hash), f(f) {}
//规定优先队列的排列顺序(按f从小到大,若f相同,则按g从小到大)
bool operator <(const Chess &t)const {
if (f == t.f)return g[hash] > g[t.hash];
return f > t.f;
}
};
//A*算法
void A_star(int start, int f) {
priority_queue<Chess> q;
q.push(Chess(start, f));
int preHash, hash, state[n], space, preH;
while (!q.empty()) {
//取出节点
Chess preChess = q.top();
preHash = preChess.hash;
if (preHash == aim) {
printPath();
return;
}
q.pop();
preH = preChess.f - g[preHash];
reverseCantor(preHash, state, space);
for (int i = 0; i < 4; ++i) {
int tx = space / 3 + dir[i][0];
int ty = space % 3 + dir[i][1];
if (tx < 0 || tx>2 || ty < 0 || ty>2)continue;
int tz = 3 * tx + ty;
state[space] = state[tz];
state[tz] = 0;
hash = cantor(state);
//没访问过
if (!visit[hash]) {
step[hash] = direct[i];
g[hash] = g[preHash] + 1;
visit[hash] = true;
parent[hash] = preHash;
q.push(Chess(hash, g[hash] + h(state)));
}
state[tz] = state[space];
state[space] = 0;
}
}
printf("unsolvable\n");
}
int getInv(int s[]) {
//求逆序数,如果逆序数和目标序列的逆序数奇偶相同,则说明是有解的
//目标序列逆序数为0,是偶数
int cnt = 0;
for (int i = 1; i < n; ++i) {
if (s[i] == 0)continue;
for (int j = 0; j < i; ++j) {
if (s[j] == 0)continue;
if (s[i] < s[j])
++cnt;
}
}
//如果cnt是偶数,则返回的是0.如果cnt是奇数,则返回的是1
//返回1,则说明无解
return cnt & 1;
}
int main() {
char x;
int a[n];
for (int i = 0; i < n; ++i) {
scanf(" %c", &x);
if (x == 'x')a[i] = 0;
else a[i] = x - '0';
}
if (getInv(a) == 1) {
printf("unsolvable\n");
}
else {
int hash = cantor(a);
visit[hash] = true;
parent[hash] = -1;
g[hash] = 0;
A_star(hash, h(a));
}
return 0;
}