#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <string>

#define pb push_back
#define all(c) (c).begin(), (c).end()

using namespace std;

#define N 8
#define BUFSIZE 32
char buf[BUFSIZE];
int d[4] = { 4, -4, 1, -1 };

int intpow(int x, int n)
{
	int res = 1;
	for (int i = 0; i < n; ++i) res *= x;
	return res;
}

int main()
{
	const int goal = 1234567;
	while (fgets(buf, BUFSIZE, stdin) != NULL) {
		int v = 0;
		char* p = strtok(buf, " ");
		while (p != NULL) { v = v * 10 + *p - '0'; p = strtok(NULL, " "); }
		queue<int> q;
		map<int, int> m;
		q.push(v);
		m[v] = 0;
		int ans = 0;
		while (!q.empty()) {
			int t = q.front();
			q.pop();
			if (t == goal) { ans = m[t]; break; }
			int z;
			int u = t;
			for (z = 0; z < N; ++z) {
				if (u % 10 == 0) break;
				u /= 10;
			}

			for (int i = 0; i < 4; ++i) {
				int k = z + d[i];
				if (k < 0 || k > 7) continue;
				if (z == 3 && k == 4 || z == 4 && k == 3) continue;
				int next = t;
				int d = next / intpow(10, k) % 10;
				next -= d * intpow(10, k);
				next += d * intpow(10, z);
				if (m.find(next) == m.end()) {
					m[next] = m[t] + 1;
					q.push(next);
				}
			}
		}
		printf("%d\n", ans);
	}
	return 0;
}