//config = { input: 'tmp', newline: '\r\n' }; // win
config = { input: '/dev/stdin', newline: '\n' }; // linux

const assert = require('assert');

const SIZE = 9;

init = require('fs').readFileSync(config.input, 'ascii')
  .trim()
  .split(config.newline)
  .join('')
  .replace(/ /g, '');
goal = [];
for (i = 1; i < SIZE; i++) goal.push(i);
goal = goal.join('') + '0';

cnt = 0;
step = {};
next = [];
function register_string(str, next, cnt) {
  if (!step.hasOwnProperty(str)) {
    step[str] = cnt;
    next.push(str);
  }
}
register_string(init, next, cnt);

function switch_array(ary, i, j) {
  var tmp = ary[i];
  ary[i] = ary[j];
  ary[j] = tmp;
}

function register(ary, next, i, j, cnt) {
  switch_array(ary, i, j);
  register_string(ary.join(''), next, cnt);
  switch_array(ary, i, j);
}

function widen(cur) {
  var next = [], i, ary, idx0;
  cnt++;
  for (i in cur) {
    ary = cur[i].split('');
    idx0 = ary.indexOf('0');
    if (idx0 === 0) {
      register(ary, next, 0, 1, cnt);
      register(ary, next, 0, 3, cnt);
    } else if (idx0 === 1) {
      register(ary, next, 1, 0, cnt);
      register(ary, next, 1, 2, cnt);
      register(ary, next, 1, 4, cnt);
    } else if (idx0 === 2) {
      register(ary, next, 2, 1, cnt);
      register(ary, next, 2, 5, cnt);
    } else if (idx0 === 3) {
      register(ary, next, 3, 0, cnt);
      register(ary, next, 3, 4, cnt);
      register(ary, next, 3, 6, cnt);
    } else if (idx0 === 4) {
      register(ary, next, 4, 1, cnt);
      register(ary, next, 4, 3, cnt);
      register(ary, next, 4, 5, cnt);
      register(ary, next, 4, 7, cnt);
    } else if (idx0 === 5) {
      register(ary, next, 5, 2, cnt);
      register(ary, next, 5, 4, cnt);
      register(ary, next, 5, 8, cnt);
    } else if (idx0 === 6) {
      register(ary, next, 6, 3, cnt);
      register(ary, next, 6, 7, cnt);
    } else if (idx0 === 7) {
      register(ary, next, 7, 4, cnt);
      register(ary, next, 7, 6, cnt);
      register(ary, next, 7, 8, cnt);
    } else if (idx0 === 8) {
      register(ary, next, 8, 5, cnt);
      register(ary, next, 8, 7, cnt);
    }
  }
  return next;
}

while (next.indexOf(goal) === -1)
  next = widen(next);
console.log(cnt);