#include <bits/stdc++.h>
#include <cstring>
using namespace std;
queue<string> a;
queue<int>q;
int space;
string goal;
int fx[6] {-3,-1,1,3};
map <string,int> p;
int bfs(string x) {
a.push(x);
int cnt=0;
q.push(0);
while(!a.empty()) {
cnt++;
string b=a.front();
int t=q.front();
if(b==goal) {
return t;
}
space=b.find('0');
q.pop();
a.pop();
for(int i=0; i<4; i++) {
int nx=space+fx[i];
if(nx<0 or nx>8 or (space==3 and fx[i]==-1) or (space==2 and fx[i]==1) or (space ==5 and fx[i]==1) or (space == 6 and fx[i]==-1) or (space==2 and fx[i]==-3) or (space==8 and (fx[i]==1 or fx[i]==3)) or (space == 6 and (fx[i]==-1 or fx[i]==3))) continue;
if(space==7&&fx[i]==3)continue;
if(space==1&&fx[i]==-3)continue;
if(space==1&&(fx[i]==-3||fx[i]==-1))continue;
swap(b[space],b[nx])
if(!p.count(b)) {
p.insert({b,cnt});
a.push(b);
q.push(t+1);
}
swap(b[space],b[nx]);
}
}
return -1;
}
int main() {
string s;
cin>>s;
p[s]=0;
goal="123804765";
if(s==goal) cout<<0;
else {
cout<<bfs(s);
}
}
58pts求调