#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
using namespace std;
int bfs(string state)
{
queue<string> q;
q.push(state);//入队
unordered_map<string, int> d;//利用hash表标记移动
d[state] = 0;//初始化状态,标记移动次数为0;
int distance = 0;
int dx[] = { 1,0,-1,0 }, dy[] = { 0,1,0,-1 };//上下左右四个方向移动
string end = "12345678x";
while (q.size())
{
auto start = q.front();
q.pop();//BFS标准流程
if (start == end)
{
return d[start];
}
distance = d[start];
int t = start.find('x');
for (int i = 0; i < 4; i++)
{
int x = dx[i] + t/3, y = dy[i] + t%3;//求出坐标
if (x >= 0 && x < 3 && y >= 0 && y < 3)
{
int a = x * 3, b = y;//x的下一个位置在字符串中的下标:a+b
swap(start[t], start[a + b]);
if (!d[start])
{
d[start] = distance + 1;
q.push(start);
}
swap(start[t], start[a + b]);
}
}
}
return -1;
}
int main()
{
string state;
char s;
for (int i = 0; i < 9; i++)
{
cin >> s;
state += s;
}
cout << bfs(state) << endl;
return 0;
}