#include <cstdio>
#include <queue>
#include <complex>
#include <algorithm>
using namespace std;

const int MAX_PTN = 76543211;

struct state {
  int i;
  int n;
  int t;
  state(int i, int n, int t) : i(i), n(n), t(t) {}
};

bool done[MAX_PTN];
int zi, n;

int di[4] = {4, -4, 1, -1};

int make_nextnum(state cur, int nexti)
{
  int nd = (cur.n / (int)pow(10, 7 - nexti)) % 10;
  int ret = cur.n + nd * (int)pow(10, 7 - cur.i) - nd * (int)pow(10, 7 - nexti);
  return ret;
}

int bfs()
{
  queue<state> que;
  que.push(state(zi, n, 0));
  memset(done, false, sizeof done);
  done[n] = true;

  while (!que.empty()) {
    state s = que.front(); que.pop();

    if (s.n == 1234567) return s.t;

    for (int i = 0; i < 4; i++) {
      int ni = s.i + di[i];
      int nn;

      if (s.i == 3 && di[i] == 1) continue;
      if (s.i == 4 && di[i] == -1) continue;
      if (ni < 0 || 7 < ni) continue;

      nn = make_nextnum(s, ni);

      if (done[nn]) continue;

      done[nn] = true;
      que.push(state(ni, nn, s.t + 1));
    }
  }

  return -1;
}

int solve()
{
  return bfs();
}

int main()
{

  while (true) {
    char s[32];
    int d = 10000000;

    fgets(s, 31, stdin);
    if (s[0] < '0' || '9' < s[0]) break;

    n = 0;
    for (int i = 0; i < 8; i++) {
      int a;
      a = s[2 * i] - '0';
      n += a * d;
      d /= 10;

      if (a == 0) { zi = i; }
    }

    printf("%d\n", solve());
  }

  return 0;
}
