function puzzle(){
   var obj={};
   obj["123456780"]=0;
   var dy=[-1,0,0,1];
   var dx=[0,-1,1,0];
   var V=[1,2,3,4,5,6,7,8,0];
   var P=[[V,0]];
   while(P.length>0){
      var A=P.shift();
      var arr=A[0];
      var cnt=A[1];
      var index=arr.indexOf(0);
      var y=Math.floor(index/3);
      var x=index%3;
      var yx=[arr.slice(0,3),arr.slice(3,6),arr.slice(6,9)];
      for(var i=0;i<4;i++){
         var yy=y+dy[i];
         var xx=x+dx[i];
         if(yy<0 || xx<0 || yy>=3 || xx>=3)continue;
         yx[y][x]=yx[yy][xx];
         var card=yx[yy][xx];
         yx[yy][xx]=0;
         var YX=yx[0].concat(yx[1],yx[2]);
         var str=YX.join("");
         if(obj.hasOwnProperty(str)==false){
               obj[str]=cnt+1;
               P.push([YX,cnt+1]);
         }
         yx[yy][xx]=card;
         yx[y][x]=0;
      }
   }
   return obj;
}
var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var str=(input.trim()).replace(/\n|\s/g,"");
var PUZZLE=puzzle();
console.log(PUZZLE[str]);