import java.util.*;
public class Main{
private static List<Integer>[]list=new List[]{
Arrays.asList(1,3),Arrays.asList(0,2,4),Arrays.asList(1,5),
Arrays.asList(0,4,6),Arrays.asList(1,3,5,7),Arrays.asList(2,4,8),
Arrays.asList(3,7),Arrays.asList(4,6,8),Arrays.asList(5,7)
};
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
String ss[]=sc.nextLine().split(" ");
StringBuilder sb=new StringBuilder();
for(String s:ss)sb.append(s);
String start=sb.toString();
String end="12345678x";
Queue<String>q=new LinkedList<>();
Set<String>set=new HashSet<>();
q.add(start);
set.add(start);
int res=0;
while(!q.isEmpty()){
int sz=q.size();
for(int i=0;i<sz;i++){
String cur=q.poll();
if(end.equals(cur)) {
System.out.println(res);
return ;
}
char c[]=cur.toCharArray();
int pos=0;
while(c[pos]!='x') pos++;
for(int next:list[pos]){
swap(c,pos,next);
String str=new String(c);
swap(c,pos,next);
if(!set.contains(str)){
set.add(str);
q.add(str);
}
}
}
res++;
}
System.out.println("-1");
}
private static void swap(char c[],int i,int j){
char t=c[i];c[i]=c[j];c[j]=t;
}
}