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

int dir[] = {1, -1, 2, -2};
unordered_map<string, int> dist;
string S = "12345678X", T = "87654321X";

int bfs()
{
    queue<string> q;
    q.push(S);
    dist[S] = 0;

    while (q.size())
    {
        string t = q.front();
        q.pop();

        if (t == T)
            return dist[t];

        int k = t.find('X'), distance = dist[t];
        for (int i = 0; i < 4; i++)
        {
            swap(t[k], t[(k + dir[i] + 9) % 9]);
            if (!dist.count(t))
            {
                q.push(t);
                dist[t] = distance + 1;
            }
            swap(t[k], t[(k + dir[i] + 9) % 9]);
        }
    }

    return -1;
}

int main()
{
    cout << bfs() << endl;
    return 0;
}
