#include<bits/stdc++.h>#define int long longusingnamespacestd;inth[11];bitset<387420489>vis;intswap(inti,intj,intstate){inta=(state/h[i])%9;intb=(state/h[j])%9;state+=(b-a)*h[i];state+=(a-b)*h[j];returnstate;}intsolve(ints,intt){queue<pair<int,int>>q;q.push({s,0});vis[s]=1;while(q.size()){auto[state,step]=q.front();q.pop();if(state==t)returnstep;for(inti=0;i<9;i++){if(i%3!=2){intnxt=swap(i,i+1,state);if(!vis[nxt]){q.push({nxt,step+1});vis[nxt]=1;}}if(i<6){intnxt=swap(i,i+3,state);if(!vis[nxt]){q.push({nxt,step+1});vis[nxt]=1;}}}}}signedmain(){h[0]=1;for(inti=1;i<=9;i++){h[i]=h[i-1]*9;}ints=0,t=0;for(inti=0;i<9;i++){t+=i*h[i];}for(inti=0;i<9;i++){intx;cin>>x;x--;s+=x*h[i];}if(s==t){cout<<0<<'\n';}else{cout<<solve(s,t)<<'\n';}}
#include<bits/stdc++.h>#define int long longusingnamespacestd;inth[11];intswap(inti,intj,intstate){inta=(state/h[i])%9;intb=(state/h[j])%9;state+=(b-a)*h[i];state+=(a-b)*h[j];returnstate;}intbfs(queue<int>&q,unordered_map<int,int>&mp1,unordered_map<int,int>&mp2){intm=q.size();while(m--){intstate=q.front();q.pop();function<int(int)>update=[&](intnxt){if(mp1.count(nxt)){return-1LL;}if(mp2.count(nxt)){returnmp1[state]+1+mp2[nxt];}mp1[nxt]=mp1[state]+1;q.push(nxt);return-1LL;};for(inti=0;i<9;i++){if(i%3!=2){intnxt=swap(i,i+1,state);intret=update(nxt);if(ret!=-1){returnret;}}if(i<6){intnxt=swap(i,i+3,state);intret=update(nxt);if(ret!=-1){returnret;}}}}return-1;}intsolve(ints,intt){queue<int>q1,q2;unordered_map<int,int>mp1,mp2;q1.push(s);mp1[s]=0;q2.push(t);mp2[t]=0;while(q1.size()&&q2.size()){intt=-1;if(q1.size()>q2.size()){t=bfs(q1,mp1,mp2);}else{t=bfs(q2,mp2,mp1);}if(t!=-1)returnt;}return-1;}signedmain(){h[0]=1;for(inti=1;i<=9;i++){h[i]=h[i-1]*9;}ints=0,t=0;for(inti=0;i<9;i++){t+=i*h[i];}for(inti=0;i<9;i++){intx;cin>>x;x--;s+=x*h[i];}if(s==t){cout<<0<<'\n';}else{cout<<solve(s,t)<<'\n';}}