Problem:
Chain Disappearance Puzzle

We are playing a puzzle.
An upright board with H rows by 5 columns of cells, as shown in
the figure below, is used in this puzzle.
A stone engraved with a digit, one of 1 through 9, is placed in each of
the cells.
When three or more stones in horizontally adjacent cells are engraved
with the same digit, the stones will disappear.
If there are stones in the cells above the cell with a disappeared
stone, the stones in the above cells will drop down, filling the
vacancy.

The puzzle proceeds taking the following steps.

When three or more stones in horizontally adjacent cells are
engraved with the same digit, the stones will disappear. Disappearances
of all such groups of stones take place simultaneously.

When stones are in the cells above the emptied cells, these stones drop down so that the emptied cells are filled.

After the completion of all stone drops, if one or more groups of
stones satisfy the disappearance condition, repeat by returning to the
step 1.

The score of this puzzle is the sum of the digits on the disappeared stones.

Write a program that calculates the score of given configurations of stones.

Input

The input consists of multiple datasets.
Each dataset is formed as follows.

Board height H

Stone placement of the row 1

Stone placement of the row 2

...

Stone placement of the row H

The first line specifies the height ( H ) of the puzzle board (1 ≤ H ≤ 10).
The remaining H lines give placement of stones on each of the rows from top to bottom.
The placements are given by five digits (1 through 9), separated by a space.
These digits are engraved on the five stones in the corresponding row, in the same order.

The input ends with a line with a single zero.

Output

For each dataset, output the score in a line.
Output lines may not include any characters except the digits expressing the scores.

Sample Input

1
6 9 9 9 9
5
5 9 5 5 9
5 5 6 9 9
4 6 3 6 9
3 3 2 9 9
2 2 1 1 1
10
3 5 6 5 6
2 2 2 8 3
6 2 5 9 2
7 7 7 6 1
4 6 6 4 9
8 9 1 1 8
5 6 1 8 1
6 8 2 1 2
9 6 3 3 5
5 3 8 8 8
5
1 2 3 4 5
6 7 8 9 1
2 3 4 5 6
7 8 9 1 2
3 4 5 6 7
3
2 2 8 7 4
6 5 7 7 7
8 8 9 9 9
0

Output for the Sample Input

36
38
99
0
72

Solution in Rust (judge verdict: Accepted)

#![allow(unused_imports)]
#![allow(non_snake_case)]
use std::cmp::*;
use std::collections::*;
use std::io::Write;

#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), std::io::stderr());
            writeln!(err, "{} = {:?}", e, $e).unwrap()
        })*
    };
}

fn main() {
    loop {
        let h = read::<usize>();
        if h == 0 {
            return;
        }
        let mut grid = vec![vec![]; h];
        for y in 0..h {
            grid[y] = read_vec::<usize>();
        }
        let before = grid.iter()
            .map(|ref row| row.iter().sum::<usize>())
            .sum::<usize>();
        grid.reverse();
        loop {
            let mut marked = HashSet::new();
            for y in 0..h {
                for x in 0..3 {
                    // 0 means not exists.
                    if grid[y][x] != 0
                        && grid[y][x] == grid[y][x + 1]
                        && grid[y][x] == grid[y][x + 2]
                    {
                        marked.insert((x, y));
                        marked.insert((x + 1, y));
                        marked.insert((x + 2, y));
                    }
                }
            }
            if marked.is_empty() {
                break;
            }

            // reconstruct
            let mut new_grid = vec![vec![0; 5]; h];
            let mut removed = vec![0; 5];
            for y in 0..h {
                for x in 0..5 {
                    while removed[x] + y < h && marked.contains(&(x, removed[x] + y)) {
                        removed[x] += 1;
                    }
                    if removed[x] + y >= h {
                        continue; // 0 is already set.
                    }
                    new_grid[y][x] = grid[removed[x] + y][x];
                }
            }
            grid = new_grid;
        }
        let after = grid.iter()
            .map(|ref row| row.iter().sum::<usize>())
            .sum::<usize>();
        println!("{}", before - after);
    }
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}