magic = [ [ [4, 9, 2], [3, 5, 7], [8, 1, 6] ], [ [8, 1, 6], [3, 5, 7], [4, 9, 2] ], [ [2, 9, 4], [7, 5, 3], [6, 1, 8] ], [ [6, 1, 8], [7, 5, 3], [2, 9, 4] ], [ [4, 3, 8], [9, 5, 1], [2, 7, 6] ], [ [2, 7, 6], [9, 5, 1], [4, 3, 8] ], [ [8, 3, 4], [1, 5, 9], [6, 7, 2] ], [ [6, 7, 2], [1, 5, 9], [8, 3, 4] ] ] def cost(sq1, sq2) res = 0 sq1.each_with_index do |row, i| row.each_with_index do |val, j| res += (val - sq2[i][j]).abs end end res end input = Array.new() input[0] = gets.strip.split(' ').map(&:to_i) input[1] = gets.strip.split(' ').map(&:to_i) input[2] = gets.strip.split(' ').map(&:to_i) costs = magic.map {|v| cost(input, v) } puts costs.min