vs = $stdin.each_line.drop(1).map { |row| row.split(' ').map { |c| c.to_i } }
                     .sort_by { |x, _| x }.map.with_index { |row, i| [row[0], row[1], i] }
                     .sort_by { |_, y, _| y }.map.with_index { |row, j| [row[0], row[1], row[2], j] }
v_new = []
v_new.push(vs.pop)

e_cost_sum = 0
while !vs.empty? do
  i = nil
  edge_min = nil
  vs.each.with_index do |v, _i|
    v_new.each do |u|
      next if (v[2] - u[2]).abs > 1 && (v[3] - u[3]).abs > 1
      _edge_min = [(u[0] - v[0]).abs, (u[1] - v[1]).abs].min
      if edge_min.nil? || edge_min > _edge_min
        edge_min = _edge_min
        i = _i
      end
    end
  end
  v = vs[i]
  vs.delete_at(i)
  v_new.push(v)
  e_cost_sum += edge_min
end

puts e_cost_sum