#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define repr(i, n) for (int i = (n); i >= 0; --i)
#define FOR(i, m, n) for (int i = (m); i < (n); ++i)
#define FORR(i, m, n) for (int i = (m); i >= (n); --i)
#define equals(a, b) (fabs((a) - (b)) < EPS)
using namespace std;
typedef long long ll;
const ll mod = 1000000007;
const ll mod2 = 998244353;
const int INF = 1000000005;
const long double EPS = 1e-10;

struct Puzzle {
  int f[9];
  int space;
  string path;

  bool operator < (const Puzzle &p) const {
    rep(i, 9) {
      if (f[i] == p.f[i]) continue;
      return f[i] > p.f[i];
    }
    return false;
  }
};

const int dx[4] = {-1, 0, 1, 0};
const int dy[4] = {0, -1, 0, 1};
const char dir[4] = {'u', 'l', 'd', 'r'};

bool isTarget(Puzzle p) {
  rep(i, 9) {
    if (p.f[i] != i + 1) return false;
  }
  return true;
}

string bfs(Puzzle s) {
  queue<Puzzle> Q;
  map<Puzzle, bool> V;
  Puzzle u, v;
  s.path = "";
  Q.push(s);
  V[s] = true;

  while (!Q.empty()) {
    u = Q.front();
    Q.pop();
    if (isTarget(u)) return u.path;
    int sx = u.space / 3;
    int sy = u.space % 3;
    rep(r, 4) {
      int tx = sx + dx[r];
      int ty = sy + dy[r];
      if (tx < 0 || ty < 0 || tx >= 3 || ty >= 3) continue;
      v = u;
      swap(v.f[u.space], v.f[tx * 3 + ty]);
      v.space = tx * 3 + ty;
      if (!V[v]) {
        V[v] = true;
        v.path += dir[r];
        Q.push(v);
      }
    }
  }
}

int main() {
  Puzzle in;

  rep(i, 9) {
    cin >> in.f[i];
    if (in.f[i] == 0) {
      in.f[i] = 9;
      in.space = i;
    }
  }
  string ans = bfs(in);
  cout << ans.size() << endl;

  
  return 0;
}
