#include <algorithm>
#include <bitset>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <utility>
using namespace std;

#define ABS(a) (((a) >= 0) ? (a) : -(a))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) > (b) ? (b) : (a))
#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 REP(i, n) for (int i = 0; i < n; ++i)
#define int long long

typedef long long ll;
typedef pair<int, int> Pair;

const int kMaxH = 1000;
const int kMaxW = 1000;
const int kInf = 1000000000;

int ans = 0;

int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, -1, 0, 1};

class Field {
public:
  int f[2][4];
  int zx, zy;
  int cnt;

  string Pattern() {
    string p;
    REP(i, 2) { REP(j, 4) { p.push_back('0'+f[i][j]); } }
    return p;
  }

  bool IsCompleted() {
    int z = 0;
    REP(i, 2) { REP(j, 4) { if (f[i][j] != z++) { return false; } } }
    return true;
  }

  bool MoveFrom(Field f0, int i) {
    REP(i, 2) { REP(j, 4) { f[i][j] = f0.f[i][j]; } }
    zx = f0.zx; zy = f0.zy;
    cnt = f0.cnt;

    int nx = zx+dx[i]; int ny = zy+dy[i];
    if (0 <= nx && nx < 2 && 0 <= ny && ny < 4) {
      int tmp = f[nx][ny];
      f[nx][ny] = f[zx][zy];
      f[zx][zy] = tmp;
      zx = nx; zy = ny;
      ++cnt;
      return true;
    }
    return false;
  }
};

int Bfs(Field f0) {
  set<string> pattern;

  queue<Field> que;
  pattern.insert(f0.Pattern());
  que.push(f0);

  while (que.size()) {
    Field f = que.front(); que.pop();
    // cout << f.cnt << endl;
    if (f.IsCompleted()) { return f.cnt; }
    REP(i, 4) {
      Field nf;
      if (nf.MoveFrom(f, i)) {
        auto r = pattern.insert(nf.Pattern());
        if (r.second) { que.push(nf); }
      }
    }
  }

  return -1;
}

signed main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  while (true) {
    Field f0;
    REP(i, 2) {
      REP(j, 4) {
        cin >> f0.f[i][j];
        if (i == 0 && j == 0 && cin.fail()) { goto r; }
      }
    }
    REP(i, 2) { REP(j, 4) { if (f0.f[i][j] == 0) { f0.zx = i; f0.zy = j; } } }
    f0.cnt = 0;
    ans = Bfs(f0);
    cout << ans << endl;
  }
r:
  return 0;
}

