#include <iostream>
//#include <cstdio>
//#include <cmath>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
//#include <set>
#include <queue>
//#include <limits>
#include <sstream>
//#include <functional>
using namespace std;

#define len(array)  (sizeof (array) / sizeof *(array))
#define rep(i, s, e) for(int i = s;i < e;i++)
#define rrep(i, e, s) for(int i = e;s <= i;i--)
#define mfill(a, v) fill(a, a + len(a), v)
#define mfill2(a, v, t) fill((t *)a, (t *)(a + len(a)), v)
#define vsort(v) sort(v.begin(), v.end())
#define rvsort(v, t) sort(v.begin(), v.end(), greater<t>())
#define asort(a) sort(a, a + len(a))
#define rasort(a, t) sort(a, a + len(a), greater<t>())
typedef unsigned int ui;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
const int INF = (int)1e9;
const int MOD = (int)1e9 + 7;
const double EPS = 1e-10;
const int dx[] = {1, -1, 0, 0, 1, -1, -1, 1};
const int dy[] = {0, 0, 1, -1, -1, -1, 1, 1};
const int weight[] = {0,1,10,100,1000,10000,100000,1000000,10000000};

string remChar(string s, char c){
  s.erase(remove(s.begin(), s.end(), c), s.end());
  return s;
}
int s2i(string Text){
  int Number;
  if ( ! (istringstream(Text) >> Number) ) Number = 0;
  return Number;
}
string replace (string str, const string& from, const string& to) {
  string::size_type pos = 0;
  while(pos = str.find(from, pos), pos != string::npos) {
	str.replace(pos, from.length(), to);
	pos += to.length();
  }
  return str;
}
int exchange(int base, int a, int b){
  int ret = base;
  int na = (base % weight[a+1]) / weight[a];
  int nb = (base % weight[b+1]) / weight[b];
  ret -= na*weight[a] + nb*weight[b];
  ret += na*weight[b] + nb*weight[a];
  return ret;
}
typedef struct P2{
  int num, depth, pos;
} p2;

void doIt(){
  string s;
  map<int, int> m;
  queue<p2> q;
  p2 p;
  int trades[8][3] = {{2, 5, -1},
					  {1, 3, 6},
					  {2, 4, 7},
					  {3, 8, -1},
					  {1, 6, -1},
					  {2, 5, 7},
					  {3, 6, 8},
					  {4, 7, -1}
  };
  p.num = 81234567;
  p.depth = 0;
  p.pos = 8;
  q.push(p);
  m[81234567] = 0;
  while(!q.empty()){
	p2 t = q.front();
	q.pop();
	rep(i, 0, 3){
	  if(trades[t.pos-1][i] != -1){
		int tmp = exchange(t.num, t.pos, trades[t.pos-1][i]);
		if(m.count(tmp) == 0){
		  p2 t1;
		  m[tmp] = t.depth + 1;
		  t1.num = tmp;
		  t1.depth = t.depth + 1;
		  t1.pos = trades[t.pos-1][i];
		  q.push(t1);
		}
	  }
	}
  }
  while(getline(cin, s)){
	int t = s2i(replace(remChar(s, ' '), "0", "8"));
	cout << m[t] << endl;
  }
}

int main() {
  doIt();
  //cout << exchange(12345678, 8, 7) << endl;
  return 0;
}