#include <algorithm>
#include <iostream>
#include <queue>
#include <unordered_map>
using namespace std;
using PIS = pair<int, string>;
const string target = "123804765";
string start;
int h(string str) {
int res = 0;
for (int i = 0; i < 9; i++) {
if (target[i] != str[i] && str[i] != '0')
res++;
}
return res;
}
int bfs() {
priority_queue<PIS, vector<PIS>, greater<PIS>> q;
unordered_map<string, int> dist;
q.emplace(h(start), start);
dist[start] = 0;
int dx[] = { 1, -1, 0, 0 }, dy[] = { 0, 0, 1, -1 };
while (q.size()) {
auto t = q.top();
q.pop();
const string src = t.second;
int px = src.find('0') / 3, py = src.find('0') % 3;
for (int i = 0; i < 4; ++i) {
int x = px + dx[i], y = py + dy[i];
if (x < 0 || x >= 3 || y < 0 || y >= 3)
continue;
string st = src;
swap(st[x * 3 + y], st[px * 3 + py]);
if (!dist.count(st) || dist[st] > dist[src] + 1) {
dist[st] = dist[src] + 1;
if (st == target)
return dist[st];
q.emplace(t.first + h(st), st);
}
}
}
return -1;
}
int main() {
#ifndef ONLINE_JUDGE
freopen(".in", "r", stdin);
#else
cin.tie(0)->sync_with_stdio(0);
#endif
cin >> start;
cout << bfs();
return 0;
}