#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <cassert>
#include <climits>
#include <numeric>
#include <functional>
#include <time.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> Pii;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define FOR(i, a, b) for (int i = (int)a; i <= (int)b; i++)
template<class T> void checkmin(T &a, T b) { if (b < a) a = b; }
template<class T> void checkmax(T &a, T b) { if (b > a) a = b; }

const int H = 2, W = 4;
int di[4] { 0, 0, -1, 1 };
int dj[4] { -1, 1, 0, 0 };
int GoalMask;

int Get(int i, int j, int mask) {
    return (mask >> (3 * (i * W + j))) & 7;
}
void Set(int i, int j, int num, int &mask) {
    mask &= ~(7 << (3 * (i * W + j)));
    mask |= num << (3 * (i * W + j));
}

bool IsInside(int i, int j) {
    return i >= 0 && i < H && j >= 0 && j < W;
}

bool Seen[1 << (3 * 8)];

int Solve(int mask) {
    queue<int> que;
    memset(Seen, 0, sizeof(Seen));
    int si, sj;
    rep(i, H)rep(j, W)if (Get(i, j, mask) == 0) { si = i; sj = j; }
    que.push(mask);
    que.push(si);
    que.push(sj);
    que.push(0);

    while (!que.empty()) {
        mask = que.front(); que.pop();
        int i = que.front(); que.pop();
        int j = que.front(); que.pop();
        int cost = que.front(); que.pop();
        if (mask == GoalMask) return cost;

        for (int d = 0; d < 4; d++) {
            int ni = i + di[d], nj = j + dj[d];
            if (IsInside(ni, nj)) {
                int next = mask;
                Set(i, j, Get(ni, nj, next), next);
                Set(ni, nj, 0, next);
                if (!Seen[next]) {
                    Seen[next] = true;
                    que.push(next);
                    que.push(ni);
                    que.push(nj);
                    que.push(cost + 1);
                }
            }
        }
    }
    return -1;
}

int main() {
    GoalMask = 0;
    rep(i, H) rep(j, W) Set(i, j, i * W + j, GoalMask);
    int x;
    while (scanf("%d", &x) != EOF) {
        int mask = 0;
        Set(0, 0, x, mask);
        rep(i, H) rep(j, W) if (i != 0 || j != 0) {
            scanf("%d", &x);
            Set(i, j, x, mask);
        }
        printf("%d\n", Solve(mask));
    }

    return 0;
}