#include<cstdio>
#include<cstdlib>
#include<cstring>
struct point{int a;char b,c,d;};
int ys,mb;
point p[362880];
/*
int a[362880];//?洢??
char b[362880];//?洢0??λ??
char c[362880];//?洢????
char d[362880];//?洢???????????
*/
int cc,now;//cc???????????now??????????
bool ok=false;
int ans;
int find0(int x)
{
char temp[10];
sprintf(temp,"%09d",x);
return strchr(temp,'0')-temp;
}
point build(int x,int y)
{
point z;
char temp[10],ch;
sprintf(temp,"%09d",p[x].a);
ch=temp[p[x].b];temp[p[x].b]=temp[y];temp[y]=ch;
sscanf(temp,"%d",&z.a);
z.b=y;
z.c=p[x].c+1;
z.d=p[x].d;
return z;
}
int check(point x)
{
for (int i=1;i<=cc;i++)//?????????????????????????
if (x.a==p[i].a)
if (x.d==p[i].d) return 0;
else {ok=true;ans=x.c+p[i].c;break;}
return 1;
}
int main()
{
int x,y,t=0;
point temp;
scanf("%d",&ys);
mb=123804765;
//mb=123456780;
p[1].a=ys;p[1].b=find0(ys);p[1].c=0;p[1].d=0;
p[2].a=mb;p[2].b=find0(mb);p[2].c=0;p[2].d=1;
cc=2;now=1;
while(now<=cc && ok==false)
{
//if (t!=c[now])
//{printf("%d %d\n",c[now],now);t=c[now];}
x=p[now].b;
//???
y=x-3;
if (y>=0) {temp=build(now,y);if (check(temp)==1) p[++cc]=temp;}
//?·?
y=x+3;
if (y<9) {temp=build(now,y);if (check(temp)==1) p[++cc]=temp;}
//????
y=x-1;
if (x%3!=0) {temp=build(now,y);if (check(temp)==1) p[++cc]=temp;}
//???
y=x+1;
if (x%3!=2) {temp=build(now,y);if (check(temp)==1) p[++cc]=temp;}
now++;
}
printf("%d",ans);
}