#include <bits/stdc++.h>
using namespace std;
#define ios ios::sync_with_stdio(false), cin.tie(nullptr);
#define endl '\n';
int dx[] = {0, 0, 0, 1, -1}, dy[] = {0, 1, -1, 0, 0};
bool flag = false;
int sx, sy;
const int goal[6][6] = {
{0, 0, 0, 0},
{0, 1, 2, 3},
{0, 8, 0, 4},
{0, 7, 6, 5},
};
int mp[5][5];
int value()
{
int cnt = 0;
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
if (mp[i][j] != goal[i][j])
{
cnt++;
}
}
}
return cnt;
}
int safe(int x, int y)
{
if (x > 3 || x < 1 || y > 3 || y < 1)
{
return 0;
}
return 1;
}
void A_star(int dep, int x, int y, int maxdep)
{
if (dep == maxdep)
{
if (!value())
{
flag = true;
return;
}
}
for (int i = 1; i <= 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (!safe(xx, yy))
{
continue;
}
swap(mp[x][y], mp[xx][yy]);
int val = value();
if (val + dep <= maxdep)
A_star(dep + 1, xx, yy, maxdep);
swap(mp[x][y], mp[xx][yy]);
}
}
int main()
{
ios;
string s;
int tot = 0;
cin >> s;
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
mp[i][j] = s[tot++] - '0';
if (mp[i][j] == 0)
{
sx = i, sy = j;
}
}
}
if (!value())
{
cout << 0 << endl;
return 0;
}
for (int i = 0;; i++)
{
A_star(0, sx, sy, i);
if (flag)
{
cout << i << endl;
return 0;
}
}
return 0;
}