Problem:
MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

8 Puzzle

The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.

In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.

1 3 0
4 2 5
7 8 6

You can move a piece toward the empty space at one step. Your goal is to make the pieces the following configuration in the shortest move (fewest steps).

1 2 3
4 5 6
7 8 0

Write a program which reads an initial state of the puzzle and prints the fewest steps to solve the puzzle.

Input

The $3 \times 3$ integers denoting the pieces or space are given.

Output

Print the fewest steps in a line.

Constraints

There is a solution.

Sample Input

1 3 0
4 2 5
7 8 6

Sample Output

4

Solution in C++14 (judge verdict: Accepted)

#include <iostream>
#include <map>
#include <queue>
#include <vector>
#define N 3
#define N2 9
using namespace std;

struct game{
  int b[N2];
  bool operator < (const game &other) const{
    for(int i=0;i<N2;i++){
      if(b[i]<other.b[i]){
        return true;
      }else if(b[i]>other.b[i]){
        return false;
      }
    }
    return false;
  }
};
game g;
map<game,int> checked;
queue<game> q;

void print(game _g){
  for(int i=0;i<N2;i++)
    printf("%d ",_g.b[i]);
  printf("\n");
}

bool clear(game _g){
  for(int i=0;i<N2;i++){
    if(_g.b[i]!=i+1) return false;
  }
  return true;
}

int solve(){
  q.push(g);
  checked.insert(make_pair(g,0));
  int depth;
  while(!q.empty()){
    g=q.front();q.pop();
    depth=checked[g];
    if(clear(g)){ return depth; }
    int w;
    for(int i=0;i<N2;i++){
      if(g.b[i]==N2) {
        w=i;
        break;
      }
    }
    vector<int> v;
    if(w%N<N-1) v.push_back(1);
    if(w%N>0  ) v.push_back(-1);
    if(w/N<N-1) v.push_back(N);
    if(w/N>0  ) v.push_back(-N);
    for(int i:v){
      game gt=g;
      swap(gt.b[w],gt.b[w+i]);
      if(checked.find(gt)==checked.end()){
        q.push(gt);
        checked.insert(make_pair(gt,depth+1));
      }
    }
  }
  return -1;
}


int main(){
  for(int i=0;i<N2;i++) {
    int tmp; cin>>tmp;
    if(tmp==0) tmp=N2;
    g.b[i]=tmp;
  }

  cout<<solve()<<endl;
}