#include <bits/stdc++.h>
//#include <iostream>
//#include <queue>
using namespace std;

int n=2,m=4;
int _a[2][4];
int b[2100000];

int next(){
	return scanf("%d %d %d %d %d %d %d %d",&_a[0][0],&_a[0][1],&_a[0][2],&_a[0][3],&_a[1][0],&_a[1][1],&_a[1][2],&_a[1][3]);
}

int getoi(){
	int x = 0;
	for(int i = 0; i < n; i++ ) {
		for(int j = 0; j < m; j++ ) {
			x<<=3;
			x|=_a[i][j];
		}
	}
	return x;
}

int geti(int x){
	int i=0;
	for(;i<8;i++){
//		printf("\t\t int geti i:%d  x&7 = %d\n",i,x&7);
		if(x&7){
			x>>=3;
		}else {
			return i;
		}
	}
	return i;
}

int change(int x,int i,int j){
//	printf("\t\tchagestart:(%d,%d,%d)\n",x,i,j);
	int a = (x&(7<<j))>>j;
//	printf("\t\t\tto a:%d\n",a);
	int y = x&(~(7<<j));
//	printf("\t\t\tto y:%d\n",y);
	y |= a<<i;
//	printf("\t\t\tto y:%d\n",y);
	return y;
}

int main(){
	while(~next()) {
		memset(b,0,sizeof(b));
		queue<int> q;
		queue<int> direction;
		q.push(getoi());
		b[getoi()&2097151] = 1;
//		printf("oi:%d   %d\n",getoi(),b[getoi()&2097151]);
		while(!q.empty()){
			int x = q.front();
			q.pop();
//			printf("x = %d    %d\n",x,b[x&2097151]);
			if(x==342391)break;
			int oi = geti(x);
			direction.push(change(x,oi*3,((4+oi)&7)*3));
			if(oi%4!=0)direction.push(change(x,oi*3,(oi-1)*3));
			if(oi%4!=3)direction.push(change(x,oi*3,(oi+1)*3));
			while(!direction.empty()){
				int y = direction.front();
//				printf("\ty = %d\n",y);
				direction.pop();
				if(b[y&2097151]==0){
					b[y&2097151] = b[x&2097151] + 1;
					q.push(y);
				}
			}
		}
		if(b[342391] == 0)
			cout<<"error"<<endl;
		else  
			cout<<b[342391]-1<<endl;
	}
	return 0;
}
