#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;

class Puzzle {
public:
	int p[8];
	int n;

	bool is_over()
	{
		for (int i = 0; i < 8; i++) {
			if (p[i] == i) return true;
		}
		return false;
	}

	int find_zero()
	{
		for (int i = 0; i < 8; i++) {
			if (0 == p[i]) return i;
		}
	}

	void swap_up()
	{
		int zero = find_zero();
		if (zero >= 4 && zero <= 7) {
			swap(p[zero], p[zero - 4]);
		}
	}
	void swap_down()
	{
		int zero = find_zero();
		if (zero >= 0 && zero <= 3) {
			swap(p[zero], p[zero + 4]);
		}
	}
	void swap_right()
	{
		int zero = find_zero();
		if (zero != 3 && zero != 7) {
			swap(p[zero], p[zero + 1]);
		}
	}

	void swap_left()
	{
		int zero = find_zero();
		if (zero != 0 && zero != 4) {
			swap(p[zero], p[zero - 1]);
		}
	}
};

int main()
{

		Puzzle now;
		for (int i = 0 ; i <= 8; i++) {
			cin >> now.p[i];
		}
		now.n = 0;

		queue<Puzzle> que;
		que.push(now);

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

			if (now.is_over()) {
				cout << now.n << endl;
				break;
			}

			Puzzle U = now; U.swap_up();    now.n++; que.push(U);
			Puzzle D = now; D.swap_down();  now.n++; que.push(D);
			Puzzle R = now; R.swap_right(); now.n++; que.push(R);
			Puzzle L = now; L.swap_left();  now.n++; que.push(L);
		}
	
	return 0;
}