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 Rust (judge verdict: Accepted)

pub fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

pub fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}

pub fn read_vec2<T: std::str::FromStr>(n: usize) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}

pub fn read_col<T: std::str::FromStr>(n: usize) -> Vec<T> {
    (0..n).map(|_| read()).collect()
}

fn fact(n: usize) -> usize {
    if n == 0 {
        1
    } else {
        n * fact(n - 1)
    }
}

fn encode(v: &Vec<u8>) -> usize {
    let n: usize = v.len();
    if n == 1 {
        return 0;
    }
    let mut c = 0;
    for i in 0..n {
        if v[i] < v[0] {
            c += 1;
        }
    }
    let mut nv = vec![];
    for i in 1..n {
        nv.push(v[i]);
    }
    c * fact(n - 1) + encode(&nv)
}

use std::collections::VecDeque;

fn next(v: &Vec<u8>, check: &mut Vec<bool>) -> Vec<Vec<u8>> {
    let mut i = 0;
    for j in 0..9 {
        if v[j] == 0 {
            i = j;
            break;
        }
    }
    let mut ret = vec![];
    if i % 3 != 0 {
        let mut n = v.clone();
        let tmp = n[i];
        n[i] = n[i - 1];
        n[i - 1] = tmp;
        let c = encode(&n);
        if !check[c] {
            check[c] = true;
            ret.push(n);
        }
    }
    if i % 3 != 2 {
        let mut n = v.clone();
        let tmp = n[i];
        n[i] = n[i + 1];
        n[i + 1] = tmp;
        let c = encode(&n);
        if !check[c] {
            check[c] = true;
            ret.push(n);
        }
    }
    if i > 2 {
        let mut n = v.clone();
        let tmp = n[i];
        n[i] = n[i - 3];
        n[i - 3] = tmp;
        let c = encode(&n);
        if !check[c] {
            check[c] = true;
            ret.push(n);
        }
    }
    if i < 6 {
        let mut n = v.clone();
        let tmp = n[i];
        n[i] = n[i + 3];
        n[i + 3] = tmp;
        let c = encode(&n);
        if !check[c] {
            check[c] = true;
            ret.push(n);
        }
    }
    ret
}

fn main() {
    let mut v: Vec<u8> = vec![];
    let t: Vec<u8> = read_vec();
    for a in t {
        v.push(a);
    }
    let t: Vec<u8> = read_vec();
    for a in t {
        v.push(a);
    }
    let t: Vec<u8> = read_vec();
    for a in t {
        v.push(a);
    }

    let goal = encode(&vec![1, 2, 3, 4, 5, 6, 7, 8, 0]);

    let mut check: Vec<bool> = vec![false; 362880];
    let mut vd = VecDeque::new();
    check[encode(&v)] = true;
    vd.push_back((v, 0));

    loop {
        let (v, d) = vd.pop_front().unwrap();
        if encode(&v) == goal {
            println!("{}", d);
            break;
        }
        for n in next(&v, &mut check) {
            vd.push_back((n, d + 1));
        }
    }
}