# [POJ 1077] Eight【双向BFS】

• 2017-12-31
• 0
• 0

## Problem:

 Time Limit: 1000MS Memory Limit: 65536K 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:

1  2  3  4    1  2  3  4    1  2  3  4    1  2  3  4
5  6  7  8    5  6  7  8    5  6  7  8    5  6  7  8
9  x 10 12    9 10  x 12    9 10 11 12    9 10 11 12
13 14 11 15   13 14 11 15   13 14  x 15   13 14 15  x

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

Source

South Central USA 1998

## Solution:

1. #define 宏函数时一定要注意多打括号，避免运算时因优先级出错。
2. 双向 BFS 处理相遇时由于要输出路径，必须分两类讨论。

### 康托展开(Cantor Expansion)：

• 将序列 {a1, a2, ..., an} 展开为正整数 X, 表示该序列为全排列中的第 X 项。
• 设 ri 表示 ai+1 ~ an 中比 ai 小的个数，则
• X = r1·(n - 1)! + r2·(n - 2)! + ... + ri·(n - i)! + ... + rn·0!

## Code: O(n·n!), n为总格数 [3660K, 32MS]

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
const int fac[9] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320};
const int dx[4] = {0, 0,-1, 1};
const int dy[4] = {1,-1, 0, 0};

inline void getTile(int &t){
char ch = getchar();
while(ch < '0') ch = getchar();
t = (ch == 'x') ? 0 : ch - '0';
}

struct Puzzle{
int con[3][3];

inline int getCantor(){  // Cantor Expansion Hash
int cantor = 0;
for(register int i = 0; i < 9; i++){
int cnt = 0;
for(register int j = i + 1; j < 9; j++)
if(con[i / 3][i % 3] > con[j / 3][j % 3]) cnt++;
cantor += cnt * fac[8 - i];
}
return cantor;
}
} s, t;

struct Queue{
#define MAXNODE 362885

Puzzle node[MAXNODE];
int fr, re;

inline void clear() {fr = re = 0;}

inline bool empty() {return fr == re;}

inline void push(const Puzzle &x) {node[re++] = x;}

inline void pop() {if(!empty()) fr++;}

inline Puzzle front() {return node[fr];}
} q;

int prev[MAXNODE], dir[MAXNODE];  // Positions of the queue serve as subscriptions
int vis[MAXNODE], qpos[MAXNODE];  // Cantor values serve as subscriptions

#define showDir(d) putchar((d) == 0 ? 'r' : ((d) == 1 ? 'l' : ((d) == 2 ? 'u' : 'd')))
// Beware of the priority of ^(XOR) used below, remember to add a bracket around each "d" !!!

inline void displayFormer(int pos){
if(dir[pos] == -1) return;
displayFormer(prev[pos]);
showDir(dir[pos]);
}

inline void bidirectional_BFS(){
q.clear();
int sCantor = s.getCantor(), tCantor = t.getCantor();
prev[0] = dir[0] = -1, vis[sCantor] = 1, qpos[sCantor] = 0, q.push(s);
prev[1] = dir[1] = -1, vis[tCantor] = 2, qpos[tCantor] = 1, q.push(t);
while(!q.empty()){
Puzzle u = q.front();
int uCantor = u.getCantor(), Bx, By;
for(register int i = 0; i < 9; i++)
if(!u.con[i / 3][i % 3]){
Bx = i / 3, By = i % 3;
break;
}
for(register int i = 0; i < 4; i++){
int Nx = Bx + dx[i], Ny = By + dy[i];
if(Nx < 0 || Nx >= 3 || Ny < 0 || Ny >= 3) continue;
Puzzle v = u; swap(v.con[Bx][By], v.con[Nx][Ny]);  // Construct the new state
int vCantor = v.getCantor();
if(!vis[vCantor]){
prev[q.re] = q.fr, dir[q.re] = (vis[uCantor] == 1 ? i : i ^ 1);
vis[vCantor] = vis[uCantor], qpos[vCantor] = q.re;
q.push(v);
}  // Push the new-reached state at the rear of queue
if(vis[vCantor] != vis[uCantor]){
// Beware of the putting-together of 3 parts of the answer !!!
if(vis[uCantor] == 1){  // When a state "u" transfered from origin meets with another state "v" already transfered from destination
displayFormer(q.fr);  // Part 1: origin - u
showDir(i);  // Part2: u - v
for(register int curPos = qpos[vCantor]; dir[curPos] != -1; curPos = prev[curPos])
showDir(dir[curPos]);  // Part 3: v - destination
}
else{  // When a state "u" transfered from destination meets with another state "v" already transfered from origin
// All directions reverse
displayFormer(qpos[vCantor]);  // Part 1: origin - v
showDir(i ^ 1);  // Part 2: v - u
for(register int curPos = q.fr; dir[curPos] != -1; curPos = prev[curPos])
showDir(dir[curPos]);  // Part 3: u - destination
}
puts("");
return;
}
}
q.pop();
}
puts("unsolvable");
}

int main(){
for(register int i = 0; i < 9; i++) getTile(s.con[i / 3][i % 3]);
for(register int i = 0; i < 8; i++) t.con[i / 3][i % 3] = i + 1;
t.con[2][2] = 0;
bidirectional_BFS();
return 0;
}

#### 评论

darkleafin.cf
(该域名已过期且被抢注。。)
darkleafin.github.io

49750

https://github.com/Darkleafin

OPEN AT 2017.12.10

Please refresh the page if the code cannot be displayed normally.

https://visualgo.net/en

- Theme by Qzhai