def erase(line)
  ret = line.join
  (1..9).each do |i|
    5.downto(3).each do |j|
      ret.gsub!(/#{i.to_s}{#{j}}/, '0'*j)
    end
  end
  ret.split('')
end

def fall(board)
  board.transpose.map{ |l|
    l.join.delete('0').rjust(@h, '0').split('') }.transpose
end

def plus(board)
  board.flatten.map(&:to_i).reduce(:+)
end

def solve(board)
  loop do
    score = plus(board)
    board.map!{ |l| erase(l) }
    board = fall(board)
    break if score == plus(board)
  end
  plus(board)
end

while (@h = gets.to_i) != 0
  board = @h.times.map{ gets.split }
  score = plus(board)
  puts score - solve(board)
end