Chain Disappearance Puzzle
Time limit1sMemory limit256 MB
Repeatedly remove horizontal runs of three or more equal digits from a 5-column board, drop stones above into gaps, and sum the removed digits.
- Level
Easy3 of 10
- Topics
- Simulation, Matrix, Implementation
- Solved
- No attempts yet
Problem
You are playing a puzzle. The puzzle uses an upright board of rows by 5 columns of cells, as in the figure below. Each cell holds one stone engraved with a digit from 1 to 9. When three or more stones in horizontally adjacent cells carry the same digit, those stones disappear. If stones sit above a cell whose stone disappeared, they drop down and fill the vacancy.

The puzzle proceeds in the following steps.
- When three or more stones in horizontally adjacent cells carry the same digit, those stones disappear. Every group that meets the condition disappears at the same time.
- When stones sit above the emptied cells, they drop down so that the emptied cells are filled.
- After all drops finish, if one or more groups still meet the disappearance condition, return to step 1 and repeat.
The score of the puzzle is the sum of the digits on the stones that disappeared.
Write a program that computes the score of a given placement of stones.

Input
The input consists of several datasets. Each dataset has the following form.
Board height
Stone placement of row 1
Stone placement of row 2
...
Stone placement of row
The first line gives the height () of the puzzle board. The next lines give the stone placement of each row, from the top row down. A placement is five digits from 1 to 9 separated by a space, engraved on the five stones of that row in the same order.
The input ends with a line containing a single zero.
Output
For each dataset, output the score on one line. An output line contains no characters other than the digits of the score.