#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
const int INF = 100000;
const int guard = 1000000;
class Point{
	public:
		int x;
		int y;
};

int main(){
	int puzzle[3][5];
	int seven[3][5];
	int zerox,zeroy;
	int ans[8] = {0,1,2,3,4,5,6,7};
	//while(true){
		for(int i=0;i<2+1;i++){
			for(int j=0;j<4+1;j++){
				puzzle[i][j] = guard;
				seven[i][j] = INF;
			}
		}
		for(int i=1;i<2+1;i++){
			for(int j=1;j<4+1;j++){
				cin >> puzzle[i][j];
				if(puzzle[i][j]==0){
					zerox=j;
					zeroy=i;
				}
			}
		}
		queue<Point> que;
		Point p;
		p.x = zerox;
		p.y = zeroy;
		que.push(p);
		seven[p.y][p.x] = 0;
		int ans1[9];
		while(!que.empty()){
			bool flag=1;
			p = que.front();
			que.pop();
			int k=0;
			for(int i=1;i<2+1;i++){
				for(int j=1;j<4+1;j++){
					ans1[k++] = puzzle[i][j];
				}
			}
			for(int i=1;i<2+1;i++){
				for(int j=1;j<4+1;j++){
					if(memcmp(ans,ans1,8)!=0)
						flag = 0;
				}
			}
			if(flag){
				cout<< seven[p.y][p.x] << endl;
				for(int t=1;t<2+1;t++){
						for(int o=1;o<4+1;o++){
							cout << puzzle[t][o] << ' ';	
						}
							cout << endl;
					}
				break;
			}
			if(puzzle[p.y-1][p.x]!=guard && seven[p.y-1][p.x]==INF){	
				Point q;
				q.x = p.x;
				q.y = p.y-1;
				if(puzzle[p.y][p.x]<puzzle[q.y][q.x]){
					swap(puzzle[p.y][p.x],puzzle[q.y][q.x]);
					que.push(q);
					seven[q.y][q.x] = seven[p.y][p.x]+1;
				cout << "うえ\n";
				for(int t=1;t<2+1;t++){
						for(int o=1;o<4+1;o++){
							cout << puzzle[t][o] << ' ';	
						}
							cout << endl;
					}
				}
			}
			if(puzzle[p.y+1][p.x]!=guard && seven[p.y+1][p.x]==INF){
				Point q;
				q.x = p.x;
				q.y = p.y+1;
				if(puzzle[p.y][p.x]>puzzle[q.y][q.x]){
				swap(puzzle[p.y][p.x],puzzle[q.y][q.x]);
				que.push(q);
				seven[q.y][q.x] = seven[p.y][p.x]+1;
				cout << "した\n";
				for(int t=1;t<2+1;t++){
						for(int o=1;o<4+1;o++){
							cout << puzzle[t][o] << ' ';	
						}
							cout << endl;
					}
				}
			}
			if(puzzle[p.y][p.x-1]!=guard && seven[p.y][p.x-1]==INF){
				Point q;
				q.x = p.x-1;
				q.y = p.y;
				if(puzzle[p.y][p.x]<puzzle[q.y][q.x]){
				swap(puzzle[p.y][p.x],puzzle[q.y][q.x]);
				que.push(q);
				seven[q.y][q.x] = seven[p.y][p.x]+1;
				cout << "ひだり\n";
				for(int t=1;t<2+1;t++){
						for(int o=1;o<4+1;o++){
							cout << puzzle[t][o] << ' ';	
						}
							cout << endl;
					}
				}
			}	
			if(puzzle[p.y][p.x+1]!=guard && seven[p.y][p.x+1]==INF){
				Point q;
				q.x = p.x+1;
				q.y = p.y;
				if(puzzle[p.y][p.x]>puzzle[q.y][q.x]){
				swap(puzzle[p.y][p.x],puzzle[q.y][q.x]);
				que.push(q);
				seven[q.y][q.x] = seven[p.y][p.x]+1;
				cout << "みぎ\n";
				for(int t=1;t<2+1;t++){
						for(int o=1;o<4+1;o++){
							cout << puzzle[t][o] << ' ';	
						}
							cout << endl;
					}
				}
			}
					
		}
		
			
	//}
	return 0;
}