#include<vector>
#include<map>
#include<algorithm>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef vector<int> vi;
vi final(9);
int dx[]={-4,-1,1,4};

bool move(vi &c,int d){
	int z=c[8];
	if(z+dx[d]<0||z+dx[d]>7)return 0;
	if(z==3&&d==2||z==4&&d==1)return 0;
	swap(c[z],c[z+dx[d]]);
	c[8]+=dx[d];
	return 1;
}
int main(){
	rep(i,9)final[i]=i%8;
	map<vi,int> visited; visited[final]=0;
	vector<vi> frontier,next; frontier.push_back(final);
	int step=0;
	
	vi goal(9);
	while(cin>>goal[0]){
		rep(i,7){
			cin>>goal[i+1];
			if(!goal[i+1])goal[8]=i+1;
		}
		while(visited.find(goal)==visited.end()){
			rep(i,frontier.size()){
				rep(d,4){
					vi c=frontier[i];
					if(!move(c,d))continue;
					if(visited.find(c)==visited.end())next.push_back(c),visited[c]=step+1;
				}
			}
			frontier=next; next.clear();
			step++;
		}
		cout<<visited[goal]<<endl;
	}
}