// Arup Guha
// 10/15/2026
// Example of a BFS Application: Eight Puzzle

import java.util.*;

public class eightpuzzle {
	
	// MOVES[i] stores which indexes i can swap with on a move from there.
	final public static int[][] MOVES = {{1,3},{0,2,4},{1,5},{0,4,6},{1,3,5,7},
										 {2,4,8},{3,7},{4,6,8},{5,7}};

	public static HashMap<String,Integer> dist;

	public static void main(String[] args) {
		
		/*** Pre-solve all cases ***/
		getAllDist();
		
		Scanner stdin = new Scanner(System.in);
		int numCases = stdin.nextInt();
		
		// Process all cases.
		for (int loop=0; loop<numCases; loop++) {
			
			// Read in the board.
			String board = "";
			for (int i=0; i<9; i++) {
				String tmp = stdin.next();
				board = board + tmp;
			}
			
			// Output the answer for this board.
			System.out.println(dist.get(board));
		}
	}
	
	// Runs BFS and fills up dist map.
	public static void getAllDist() {
	
		// BFS set up.
		dist = new HashMap<String,Integer>();
		dist.put("123456780", 0);
		ArrayDeque<String> q = new ArrayDeque<String>();
		q.offer("123456780");
	
		// Run the BFS.
		while (q.size() > 0) {
		
			// Get the current board state.
			String cur = q.poll();
			int curD = dist.get(cur);
			
			// Get all the board states we can reach in one move.
			ArrayList<String> next = getNext(cur);
			
			// Add to queue any new board states.
			for (String x : next) {
			
				// We've been here before.
				if (dist.containsKey(x)) continue;
					
				// Update number of moves to get to this new board state.
				dist.put(x, curD+1);
				
				// Add to queue.
				q.offer(x);
			}
		}
	}
	
	// Returns the adjacent game states to the state stored in cur.
	public static ArrayList<String> getNext(String cur) {
		
		// Find where 0 is in the string.
		int zeroPos = -1;
		for (int i=0; i<cur.length(); i++)
			if (cur.charAt(i) == '0')
				zeroPos = i;
			
		ArrayList<String> res = new ArrayList<String>();
		
		// i is index into the array that stores where 0 can move to...
		for (int i=0; i<MOVES[zeroPos].length; i++) {
			int tradePos = MOVES[zeroPos][i];
			res.add(trade(cur, zeroPos, tradePos));
		}
		
		return res;
	}
	
	// Returns the result of swapping positions i and j in s.
	public static String trade(String s, int i, int j) {
		char[] tmp = s.toCharArray();
		tmp[i] = s.charAt(j);
		tmp[j] = s.charAt(i);
		return new String(tmp);
	}
	
}