#include <bits/stdc++.h>
#define rep(i, n) for(int i=0;i<n;++i)
#define FOR(i, a, b) for(int i=a;i<b;++i)
#define RFOR(i, a, b) for (int i=a;i>=b;--i)
#define ll long long
#define all(a) a.begin(),a.end()
#define ull unsigned long long
#define pb(x) push_back(x)
#define dbg(x) cout<<#x<<" : "<<(x)<<endl;
using namespace std;
const int INF = 1500000000;
const double PI = 3.14159265359;
const int mod = 1000000000 + 7;
int p;

int ipow(int x, int y) {
  int tmp = 1;
  rep(i, y) tmp *= x;
  return tmp;
}
int indexof(int x, int y) {
  rep(i, y) x /= 10;
  return x % 10;
}

int bfs() {
  int res;
  queue<pair<int, int> > que;
  que.push(make_pair(p, 1));
  while(true) {
    pair<int, int> q = que.front();
    que.pop();
    int a = q.first;
    int cnt = q.second;
    if(a == 876543210) {res = cnt; break;}
    int index;
    rep(i, 8) {
      if (a % ipow(10, i) == 0) index = i;
    }
    if (index < 4) {
      int b = a - indexof(a, index+4)*ipow(10, index+4)
                + indexof(a, index+4)*ipow(10, index);
      que.push(make_pair(b, ++cnt));
    }
    if (index < 7) {
      int b = a - indexof(a, index+1)*ipow(10, index+1)
                + indexof(a, index+1)*ipow(10, index);
      que.push(make_pair(b, ++cnt));
    }
    if (index > 1) {
      int b = a - indexof(a, index-1)*ipow(10, index-1)
                + indexof(a, index-1)*ipow(10, index);
      que.push(make_pair(b, ++cnt));
    }
    if (index > 3){
      int b = a - indexof(a, index-4)*ipow(10, index-4)
                + indexof(a, index-4)*ipow(10, index);
      que.push(make_pair(b, ++cnt));
    }
  }
  return res;
}

int main() {
  while(true) {
    p = 800000000;
    rep(i, 8) {
      int a; cin >> a;
      if(cin.eof()) break;
      p += a * ipow(10, i);
    }
    int res = bfs();
    cout << res << endl;
  }
  return 0;
}