#include<bits/stdc++.h>
using namespace std;
struct PII {
int x, y;
};
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
string first, endd = "123804765";
PII get_coord(string s) {
for (int i = 0; i < 9; i++) {
if (s[i] == '0') {
return {i / 3, i % 3};
}
}
}
int second_bfs(queue<string> &q, unordered_map<string, int> &mp1, unordered_map<string, int> &mp2) {
string u = q.front();
q.pop();
PII st = get_coord(u);
for (int i = 0; i < 4; i++) {
PII v;
v.x = st.x + dx[i];
v.y = st.y + dy[i];
if (v.x < 0 || v.x > 3 || v.y < 0 || v.y > 3) {
continue;
}
string p = u;
swap(p[st.x * 3 + st.y], p[v.x * 3 + v.y]);
if (mp2.count(p) == 1) {
return mp2[p] + 1;
}
if (mp1.count(p) == 1) {
continue;
}
mp1[p] = mp1[u] + 1;
q.push(p);
}
return -1;
}
int bfs() {
queue<string> qstart, qend;
unordered_map<string, int> mp1, mp2;
qstart.push(first);
qend.push(endd);
mp1[first] = 0;
mp2[endd] = 0;
while (qstart.size() && qend.size()) {
int ans = 0;
if (qstart.size() < qend.size()) {
ans = second_bfs(qstart, mp1, mp2);
} else {
ans = second_bfs(qend, mp2, mp1);
}
if (ans != -1) {
return ans;
}
}
return -1;
}
int main() {
cin >> first;
if (first == endd) {
cout << 0;
}
cout << bfs();
return 0;
}