#include <bits/stdc++.h>
#define N 3
using namespace std;
struct Graph{
	char r, c;
	string m;
	int cnt;
	bool ok(){
		bool ans = 1;
		for(int i=0; i<N*N; i++)
			ans &= (m[i] == (i+1) % (N*N));
		return ans;
	}
	void get(){
		for(int i=0; i<N; i++)
		for(int j=0; j<N; j++){
			cin >> cnt;
			m.push_back(cnt);
			if(cnt == 0) r = i, c = j;
		}
		cnt = 0;
	}
	bool go(int i, int j){
		int r1=i+r, c1=j+c;
		if(!legal(r1, c1)) return 0;
		m[r*N+c] = m[r1*N+c1];
		m[r1*N+c1] = 0;
		r = r1, c = c1;
		cnt++;
		return 1;
	}
	bool legal(int r1, int c1){
		return (r1>=0 && r1<N && c1>=0 && c1<N);
	}
};
queue <Graph> Q;
map <string , bool> V;
int bfs(){
	int cmd[4][2]={{1,0}, {-1,0}, {0,1}, {0,-1}};
	Graph t0,t1;
	while(!Q.empty()){
		t0 = Q.front();
		Q.pop();
		if(t0.ok()) return t0.cnt;
		for(int i=0; i<4; i++){
			t1 = t0;
			if(t1.go(cmd[i][0], cmd[i][1]))
				if(!V[t1.m])
					Q.push(t1), V[t1.m] = 1;
		}
	}
	return -1;
}
int main()
{	
	Graph a; a.get();
	Q.push(a);
	V[a.m] = 1;
	cout << bfs() << endl;
	return 0;
}


### Prompt

Please create a solution in CPP to the following problem:

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.

Constraints

* There is a solution.

Input

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

Output

Print the fewest steps in a line.

Example

Input

1 3 0
4 2 5
7 8 6


Output

4

### Response

```cpp
#include <bits/stdc++.h>
#define N 3
using namespace std;
struct Graph{
	char r, c;
	string m;
	int cnt;
	bool ok(){
		bool ans = 1;
		for(int i=0; i<N*N; i++)
			ans &= (m[i] == (i+1) % (N*N));
		return ans;
	}
	void get(){
		for(int i=0; i<N; i++)
		for(int j=0; j<N; j++){
			cin >> cnt;
			m.push_back(cnt);
			if(cnt == 0) r = i, c = j;
		}
		cnt = 0;
	}
	bool go(int i, int j){
		int r1=i+r, c1=j+c;
		if(!legal(r1, c1)) return 0;
		m[r*N+c] = m[r1*N+c1];
		m[r1*N+c1] = 0;
		r = r1, c = c1;
		cnt++;
		return 1;
	}
	bool legal(int r1, int c1){
		return (r1>=0 && r1<N && c1>=0 && c1<N);
	}
};
queue <Graph> Q;
map <string , bool> V;
int bfs(){
	int cmd[4][2]={{1,0}, {-1,0}, {0,1}, {0,-1}};
	Graph t0,t1;
	while(!Q.empty()){
		t0 = Q.front();
		Q.pop();
		if(t0.ok()) return t0.cnt;
		for(int i=0; i<4; i++){
			t1 = t0;
			if(t1.go(cmd[i][0], cmd[i][1]))
				if(!V[t1.m])
					Q.push(t1), V[t1.m] = 1;
		}
	}
	return -1;
}
int main()
{	
	Graph a; a.get();
	Q.push(a);
	V[a.m] = 1;
	cout << bfs() << endl;
	return 0;
}


```