#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<string>
using namespace std;
string dest = "123804765";
map<string, bool>hashp;
queue<pair<string,int>>q;
string pos;
int cnt;
int dx[4] = { -3,3,-1,1 };
bool rightgo(int p0, int go,int d)
{
if (go < 0 || go>8) return false;
if (p0 % 3 == 0 && d == -1) return false;
if (p0 % 3 == 2 && d == 1) return false;
return true;
}
int main()
{
cin >> pos;
q.push(make_pair(pos,0));
hashp[pos] = true;
while (!q.empty())
{
pos = q.front().first;
cnt = q.front().second;
int p0 = 0;
while (pos[p0] != '0') p0++;
q.pop();
for (int i = 0; i < 4; i++)
{
int go = p0 + dx[i];
char c;
int flag = 0;
if (rightgo(p0,go,dx[i]))
{
flag = 1;
c = pos[go];
pos[go] = '0';
pos[p0] = c;
if (hashp[pos] != true)
{
hashp[pos] = true;
q.push(make_pair(pos,cnt+1));
if (pos == dest)
{
cout << cnt + 1;
return 0;
}
}
}
if(flag==1)
{
pos[go] = c;
pos[p0] = '0';
}
}
}
return 0;
}