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 (Python):
import sys
input = sys.stdin.readline


def cal(board):
    H = len(board)
    gain = 0
    tmp = [1]*5
    for row in board:
        for i in range(1, 5):
            tmp[i] = tmp[i-1] * (row[i-1] == row[i]) + 1
        for i in range(4, -1, -1):
            if tmp[i] >= 3:
                gain += row[i] * tmp[i]
                for j in range(i, i-tmp[i], -1):
                    row[j] = 0
                break

    for col in range(5):
        i = H-1
        for row in board[::-1]:
            if row[col]:
                board[i][col] = row[col]
                i -= 1
        for i in range(i, -1, -1):
            board[i][col] = 0

    return gain


while True:
    H = int(input())
    if H == 0:
        break

    board = []
    for _ in [0]*H:
        *line, = map(int, input().split())
        board.append(line)

    score = 0
    while True:
        gain = cal(board)
        if gain == 0:
            break
        score += gain
    print(score)

Solution (Python):

import sys

while True:
    n = int(input())
    if n == 0:
        sys.exit()
    puzzle = [[] for _ in range(5)]
    
    for i in range(n):
        for j, stone in enumerate(list(map(int, input().split()))):
            puzzle[j].insert(0, stone)
            
    tmp_score = 10
    ans = 0
    while tmp_score != 0:
        tmp_score = 0
        for i in range(n - 1, -1, -1):
        
            flg = False
            for left in range(3):
                for right in range(4, 1 + left, -1):
                        tmp_list = []
                        for idx in range(left, right+1):
                            try:
                                tmp_list.append(puzzle[idx][i])
                            except:
                                tmp_list.append(0)
                        if len(set(tmp_list)) == 1 and not (0 in tmp_list):
                            tmp_score += sum(tmp_list)
                            flg = True
                            
                            for idx in range(left, right+1):
                                try:
                                    puzzle[idx].pop(i)
                                except:
                                    pass
                            break
                if flg:
                    break
        ans += tmp_score

    print(ans)

Solution (Python):
def CDP(h,w,k):
  q=[]
  ans=0
  d=-1
  m=0
  while True:
    if d==ans:break
    d=ans
    for i in range(h):
      cnt=0
      for j in range(w-1):
        if a[j][i]==a[j+1][i]:cnt+=1
        else:
          if cnt>=k-1:
            q.append((j-cnt,i,cnt+1))
          cnt=0
      if cnt>=k-1:
        q.append((w-cnt-1,i,cnt+1))      
    while q:
      j,i,cnt=q.pop()
      for c in range(cnt):
        ans+=a[j+c].pop(i)
        a[j+c].append(0)
  return ans

while True:
  h=int(input())
  if h==0:break
  b=[list(i[::-1]) for i in zip(*[input().split() for _ in range(h)])]
  a=[[int(s) for s in strs] for strs in b]
  print(CDP(h,5,3))

Solution (Python):
class Puzzle():
  def __init__(self, mat, N):
    self.mat = mat
    self.h = N
    self.score = 0

  def calc(self):
    tmp_score = self.score

    for i in range(self.h):
      for j in range(3):
        if self.mat[i][j] > 0:
          
          for k in range(5, 2, -1):
            if j+k <= 7 and k-j >= 3:
              s = set(self.mat[i][j:k])
              if len(s) == 1 and -1 not in s:
                tmp_score += list(s)[0] * (k-j)
                for l in range(j, k):
                  self.mat[i][l] = -1
                break

    if self.score >= tmp_score:
      return False
    else:
      self.score = tmp_score
      return True

  def flatten(self):
    pivot_mat = []
    for i in range(5):
      row = []
      for j in range(self.h):
        if self.mat[j][i] != -1:
          row.append(self.mat[j][i])

      short = self.h - len(row)
      if short > 0:
        row.reverse()
        for k in range(short):
          row.append(-1)
        row.reverse()
      
      pivot_mat.append(row)

    mat = [ [-1]*5 for i in range(self.h) ]
    for i in range(self.h):
      for j in range(5):
        mat[i][j] = pivot_mat[j][i]

    self.mat = mat

while True:
  h = int(input())
  if h==0: exit()
  mat = []
  for _ in range(h):
    mat.append(list(map(int,input().split())))
  puzzle = Puzzle(mat, h)

  while True:
    if puzzle.calc():
      puzzle.flatten()
    else:
      break

  print(puzzle.score)

Solution (Python):
def move(board): 
    board = [list(x) for x in zip(*board)]
    for i in range(len(board)):
        row = board[i]
        row = [i for i in row if i!=0]
        n = len(board[i]) - len(row)
        row.extend([0]*n)
        board[i] = row
    board = [list(x) for x in zip(*board)]
    return board

ls_ans = []
while(1):
    ans = 0
    H = int(input())
    if H==0:
        break
    board = []
    for h in range(H):
        C = list(map(int,input().split()))
        board.append(C)
    board = board[::-1]
    for t in range(H):
        for h in range(H):
            C = board[h]
            changed = set()
            old_c = ''
            oldold_c = ''
            streak = 0
            for i,c in enumerate(C):
                if c == old_c and c == oldold_c:
                    if streak == 0:
                        streak += 3*c
                        C[i] = C[i-1] = C[i-2] = 0
                    else:
                        streak += c
                        C[i] = 0
                else:
                    ans += streak
                    streak = 0
                oldold_c = old_c
                old_c = c
            ans += streak
            board[h] = C
        board = move(board)
    ls_ans.append(ans)

for ans in ls_ans:
    print (ans)

Solution (Python):
import sys
import itertools

import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines



while True:
    H = int(input())
    if H == 0:
        break
    B = [0] * H
    for i in range(H):
        B[i] = list(map(int, input().split()))
    W = len(B[i])

    score = 0
    while True:
        
        for i in range(H):
            start = 0
            while start < W:
                count = 1
                while start + count < W and B[i][start] == B[i][start + count]:
                    count += 1
                if count >= 3:
                    score += B[i][start] * count
                    for j in range(start, start + count):
                        B[i][j] = 0
                start += count
        
        updated = False
        for i in range(H - 1, -1, -1):
            for j in range(W - 1, -1, -1):
                if B[i][j] != 0:
                    continue
                new_col = []
                for k in range(i, -1, -1):
                    if B[k][j] == 0:
                        continue
                    new_col.append(B[k][j])
                l = 0
                for k in range(i, -1, -1):
                    if l >= len(new_col):
                        B[k][j] = 0
                    else:
                        B[k][j] = new_col[l]
                        updated = True
                    l += 1
        if not updated:
            break
    print(score)

Solution (Python):
while True:
    H = int(input())
    if H == 0:
        exit()
    L = [input().split() for _ in range(H)]
    L1 = list(reversed([l[0] for l in L]))
    L2 = list(reversed([l[1] for l in L]))
    L3 = list(reversed([l[2] for l in L]))
    L4 = list(reversed([l[3] for l in L]))
    L5 = list(reversed([l[4] for l in L]))
    ans = 0
    while True:
        changed = False
        for i in range(H):
            if L1[i] != 'X' and L1[i] == L2[i] == L3[i] == L4[i] == L5[i]:
                changed = True
                ans += 5*int(L1[i])
                L1[i] = 'X'
                L2[i] = 'X'
                L3[i] = 'X'
                L4[i] = 'X'
                L5[i] = 'X'
            elif L1[i] != 'X' and L1[i] == L2[i] == L3[i] == L4[i]:
                changed = True
                ans += 4*int(L1[i])
                L1[i] = 'X'
                L2[i] = 'X'
                L3[i] = 'X'
                L4[i] = 'X'
            elif L2[i] != 'X' and L2[i] == L3[i] == L4[i] == L5[i]:
                changed = True
                ans += 4*int(L2[i])
                L2[i] = 'X'
                L3[i] = 'X'
                L4[i] = 'X'
                L5[i] = 'X'
            elif L1[i] != 'X' and L1[i] == L2[i] == L3[i]:
                changed = True
                ans += 3*int(L1[i])
                L1[i] = 'X'
                L2[i] = 'X'
                L3[i] = 'X'
            elif L2[i] != 'X' and L2[i] == L3[i] == L4[i]:
                changed = True
                ans += 3*int(L2[i])
                L2[i] = 'X'
                L3[i] = 'X'
                L4[i] = 'X'
            elif L3[i] != 'X' and L3[i] == L4[i] == L5[i]:
                changed = True
                ans += 3*int(L3[i])
                L3[i] = 'X'
                L4[i] = 'X'
                L5[i] = 'X'
        if not changed:
            break
        L1 = list(filter(lambda x: x!='X',L1)) + ['X']*L1.count('X')
        L2 = list(filter(lambda x: x!='X',L2)) + ['X']*L2.count('X')
        L3 = list(filter(lambda x: x!='X',L3)) + ['X']*L3.count('X')
        L4 = list(filter(lambda x: x!='X',L4)) + ['X']*L4.count('X')
        L5 = list(filter(lambda x: x!='X',L5)) + ['X']*L5.count('X')
    print(ans)

Solution (Python):
H = int(input())

while H:
  Ali = [list(map(int,input().split())) for _ in range(H)]
  score = 0
  while True:
    sc = score
    for i in range(H):
      Row = Ali[i]
      
      if Row[0] == Row[1] == Row[2] == Row[3] == Row[4]:
        score += Row[0]*5
        Ali[i][0] = Ali[i][1] = Ali[i][2] = Ali[i][3] = Ali[i][4] = 0
      
      
      if Row[0] == Row[1] == Row[2] == Row[3]:
        score += Row[0]*4
        Ali[i][0] = Ali[i][1] = Ali[i][2] = Ali[i][3] = 0
      
      if Row[1] == Row[2] == Row[3] == Row[4]:
        score += Row[1]*4
        Ali[i][1] = Ali[i][2] = Ali[i][3] = Ali[i][4] = 0
      
    
      if Row[0] == Row[1] == Row[2]:
        score += Row[0]*3
        Ali[i][0] = Ali[i][1] = Ali[i][2] = 0
      
      if Row[1] == Row[2] == Row[3]:
        score += Row[1]*3
        Ali[i][1] = Ali[i][2] = Ali[i][3] = 0
      
      if Row[2] == Row[3] == Row[4]:
        score += Row[2]*3
        Ali[i][2] = Ali[i][3] = Ali[i][4] = 0
        
    if sc == score:
      break
      
    
    
    for i in range(1,H+1):
      for j in range(0,5):
        if Ali[-i][j] == 0:
          for k in range(i+1,H+1):
            if Ali[-k][j] != 0:
              Ali[-i][j] = Ali[-k][j]
              Ali[-k][j] = 0
              break
              
  print(score)
  H = int(input())

Solution (Python):
while(1):
    h = int(input())
    if not h:
        break
    a = [[] for j in range(h)]
    for i in range(h):
        a[i] = [int(i) for i in input().split()]
    ans = 0
    disap = True
    fall = True
    while(disap):
        while(disap):
            disap = False
            for i in range(h):
                if a[i][0] and all([a[i][k] == a[i][k+1] for k in range(4)]):
                    ans += a[i][0]*5
                    for k in range(5):
                        a[i][k] = 0
                    disap = True
                    fall = True
                elif a[i][0] and all([a[i][k] == a[i][k+1] for k in range(3)]):
                    ans += a[i][0]*4
                    for k in range(4):
                        a[i][k] = 0
                    disap = True
                    fall = True
                elif a[i][1] and all([a[i][k+1] == a[i][k+2] for k in range(3)]):
                    ans += a[i][1]*4
                    for k in range(4):
                        a[i][k+1] = 0
                    disap = True
                    fall = True
                elif a[i][0] and all([a[i][k] == a[i][k+1] for k in range(2)]):
                    ans += a[i][0]*3
                    for k in range(3):
                        a[i][k] = 0
                    disap = True
                    fall = True
                elif a[i][1] and all([a[i][k+1] == a[i][k+2] for k in range(2)]):
                    ans += a[i][1]*3
                    for k in range(3):
                        a[i][k+1] = 0
                    disap = True
                    fall = True
                elif a[i][2] and all([a[i][k+2] == a[i][k+3] for k in range(2)]):
                    ans += a[i][2]*3
                    for k in range(3):
                        a[i][k+2] = 0
                    disap = True
                    fall = True
        while(fall):
            fall = False
            for i in range(1, h):
                for j in range(5):
                    if a[i][j] == 0 and a[i-1][j]:
                        a[i][j], a[i-1][j] = a[i-1][j], a[i][j]
                        fall = True
                        disap = True
    print(ans)

Solution (Python):
while True:
    H = int(input())
    if H == 0:
        break
    squares = [list(map(int, input().split())) for _ in range(H)]
    score = 0
    while True:
        deleted = False
        for i in range(H):
            for j in range(5, 2, -1):
                for k in range(5 - j + 1):
                    deletable = True
                    first_num = squares[i][k]
                    if first_num == 0:
                        continue
                    for num in squares[i][k + 1:k + j]:
                        if first_num != num:
                            deletable = False
                            break
                    if deletable:
                        score += first_num * j
                        squares[i][k:k + j] = [0] * j
                        deleted = True
        
        if deleted:
            while True:
                not_falled = True
                
                for i in range(H - 1, 0, -1):
                    for k, num in enumerate(squares[i]):
                        if num == 0 and squares[i - 1][k] != 0:
                            squares[i - 1][k], squares[i][k] = squares[i][k], squares[i - 1][k]
                            not_falled = False
                if not_falled:
                    break
        else:
            break
    print(score)

Solution (Python):
def puyo_one(A):
  ans = 0
  now = 1
  for i in range(1, 5):
    if A[i] == A[i - 1]:
      now += 1
    else:
      if now >= 3:
        ans += now * A[i - 1]
      now = 1
  return ans

def puyo(A):
  p = 0
  ans = 0
  while p == 0:
    this = 0
    
    for i in range(len(A)):
      now = 1 
      for j in range(1, 5):
        if (A[i][j] == A[i][j - 1]) and (A[i][j] != 0):
          now += 1
        else:
          if now >= 3:
            this = 1
            ans += A[i][j - 1] * now 
            for k in range(j - now, j):
              A[i][k] = 0
          now = 1
      if now >= 3:
        this = 1
        ans += A[i][j - 1] * now 
        for k in range(j - now + 1, j + 1):
          A[i][k] = 0
    
    
    if this == 0:
      p = 1
    
    
    N = len(A)
    for i in range(1, N + 1):
      for j in range(5):
        if (A[N - i][j] == 0) and (i != N):
          k = 1
          while (A[N - i - k][j] == 0) and (k + i < N):
            k += 1
          A[N - i][j] = A[N - i - k][j]
          A[N - i - k][j] = 0
    
    q = 0
    while q == 0:
      if [0, 0, 0, 0, 0] in A:
        A.pop(A.index([0, 0, 0, 0, 0]))
      else:
        q = 1
    
  return ans

l = 0
while l == 0:
  H = int(input())
  if H == 0:
    quit()
  else:
    A = [0] * H
    for i in range(H):
      A[i] = list(map(int, input().split()))
      
    print(puyo(A))

Solution (Python):
from collections import Counter
while 1:
  H = int(input())
  if H == 0:
    exit()
    
  A = [[] for _ in range(5)]
  for i in range(H):
    tmp = list(map(int, input().split()))
    for j in range(5):
      A[j].append(tmp[j])
      
  for j in range(5):
    A[j] = A[j][::-1]
  
  ans = 0
  while 1:
    tmp = ans
    N = min([len(a) for a in A])
    for j in range(N):
      l = Counter([A[i][j] for i in range(5)])
      for k in range(10):
        if l[k] == 5:
          tmp += 5*k
          for i in range(5):
            A[i][j] = 'x'
          break
        elif A[0][j]==A[1][j]==A[2][j]==A[3][j]==k:
          tmp += 4*k
          for i in range(4):
            A[i][j] = 'x'
          break
        elif A[1][j]==A[2][j]==A[3][j]==A[4][j]==k:
          tmp += 4*k
          for i in range(1,5):
            A[i][j] = 'x'
          break
        elif A[0][j]==A[1][j]==A[2][j]==k:
          tmp += 3*k
          for i in range(3):
            A[i][j] = 'x'
          break
        elif A[1][j]==A[2][j]==A[3][j]==k:
          tmp += 3*k
          for i in range(1,4):
            A[i][j] = 'x'
          break
        elif A[2][j]==A[3][j]==A[4][j]==k:
          tmp += 3*k
          for i in range(2,5):
            A[i][j] = 'x'
          break
    if tmp == ans:
      break
    else:
      ans = tmp
      B = [[] for _ in range(5)]
      for i in range(5):
        for a in A[i]:
          if a != 'x':
            B[i].append(a)
      A = B
  print(ans)

Solution (Python):
while 1:
    n=int(input())
    if n==0:break
    A=[list(map(int,input().split())) for _ in range(n)]
    ans=0
    while 1:
        score=ans
        for i in range(n):
            cnt,num=0,A[i][0]
            for j in range(5):
                if A[i][j]==num:cnt +=1
                else:
                    if cnt>=3:
                        ans +=num*cnt
                        for k in range(cnt):A[i][j-k-1]=0
                    num=A[i][j]
                    cnt=1
                if j==4 and cnt>=3:
                    ans +=num*cnt
                    for k in range(cnt):A[i][j-k]=0
        B=[[-1 for _ in range(5)] for _ in range(n)]
        for i in range(5):
            cnt=n-1
            for j in range(n)[::-1]:
                if A[j][i]!=0:
                    B[j][i]=cnt
                    cnt -=1
        C=[[0 for _ in range(5)] for _ in range(n)]
        for i in range(5):
            for j in range(n):
                if B[j][i]!=-1:
                    C[B[j][i]][i]=A[j][i]
        A=C
        if score==ans:break
    print(ans)

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def S(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LS(): return input().split()

def resolve():
    while True:
        H = I()
        if H==0:
            break
        else:
            s = [LI() for _ in range(H)]

            score = 0
            while True:
                
                score_tmp = 0
                for i in range(H):
                    prev = 0
                    cnt = 1
                    for j in range(5):
                        if s[i][j]==prev:
                            cnt += 1
                        else:
                            if cnt>=3:
                                score_tmp += prev*cnt
                                for k in range(cnt):
                                    s[i][j-cnt+k] = 0
                            prev = s[i][j]
                            cnt = 1
                    if cnt>=3:
                        score_tmp += prev*cnt
                        for k in range(cnt):
                            s[i][j+1-cnt+k] = 0
                
                
                
                if score_tmp==0:
                    break
                score += score_tmp

                
                
                drop = [[0]*5 for _ in range(H)]
                for i in range(5):
                    for j in range(H-1):
                        drop[H-j-2][i] = drop[H-j-1][i] + (1 if s[H-j-1][i]==0 else 0)
                
                
                
                
                
                for i in range(5):
                    for j in range(H):
                        if drop[H-j-1][i]!=0:
                            s[H-j-1+drop[H-j-1][i]][i] = s[H-j-1][i]
                            s[H-j-1][i] = 0
                
                
                

            print(score)

if __name__ == '__main__':
    resolve()

Solution (Python):

import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

def main():
    ans = []
    while True:
        H = int(readline())
        if H == 0:
            break

        c = [[int(i) for i in readline().split()] for _ in range(H)]
        seq = [[1] for _ in range(H)]
        ans_tmp = [0]
        
        score = 0
        while True:
            
            for i, line in enumerate(c):
                for j in range(1,5):
                    if line[j] == line[j-1]:
                        seq[i][-1] += 1
                    else:
                        seq[i].append(1)
            
                acc = -1
                for s in seq[i]:
                    acc += s
                    if s >= 3:
                        score += s * line[acc]
                        for j in range(acc - s + 1, acc + 1):
                            line[j] = 0
                seq[i] = [1]

            for i in reversed(range(H)):
                for j in range(5):
                    if c[i][j] == 0:
                        for h in reversed(range(i)):
                            if c[h][j] != 0:
                                c[h][j], c[i][j] = c[i][j], c[h][j]
                                break

            ans_tmp.append(score)
            if ans_tmp[-1] == ans_tmp[-2]:
                ans.append(ans_tmp[-1])
                break

    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Solution (Python):
while True:
    H = int(input())
    if H==0:
        exit()
    board = [[0]*5 for _ in range(H+1)]
    for i in range(1,H+1):
        board[i] = list(map(int, input().split()))
    board = board[::-1]
    change = True
    score = 0
    while change==True:
        change = False
        for i in range(H-1,-1,-1):
            if len(set(board[i]))==1 and board[i][0]>0:
                score += sum(board[i])
                change = True
                for j in range(i,H):
                    board[j] = board[j+1]
            elif len(set(board[i][:4]))==1 and board[i][:4][0]>0:
                score += sum(board[i][:4])
                change = True
                for j in range(i,H):
                    board[j][:4] = board[j+1][:4]
            elif len(set(board[i][1:]))==1 and board[i][1:][0]>0:
                score += sum(board[i][1:])
                change = True
                for j in range(i,H):
                    board[j][1:] = board[j+1][1:]
            elif len(set(board[i][:3]))==1 and board[i][:3][0]>0:
                score += sum(board[i][:3])
                change = True
                for j in range(i,H):
                    board[j][:3] = board[j+1][:3]
            elif len(set(board[i][1:4]))==1 and board[i][1:4][0]>0:
                score += sum(board[i][1:4])
                change = True
                for j in range(i,H):
                    board[j][1:4] = board[j+1][1:4]
            elif len(set(board[i][2:]))==1 and board[i][2:][0]>0:
                score += sum(board[i][2:])
                change = True
                for j in range(i,H):
                    board[j][2:] = board[j+1][2:]
    print(score)

Solution (Python):

def solve():
    cnt = -1
    while 1:
        cnt += 1
        H = int(input())
        if H==0:
            break
        puzzle = [list(map(int, input().split())) for _ in range(H)]
        ans = 0
        while True:
            flg = True
            for i, row in enumerate(puzzle):
                if len(set(row))>=4:
                    continue
                streak = [-1, 1]
                for j, c in enumerate(row):
                    if c==-1:
                        streak[0] = -1
                        streak[1] = 1
                        continue
                    if c==streak[0]:
                        streak[1]+=1
                        if streak[1]==3:
                            flg = False
                            ans += c*3
                            puzzle[i][j-2:j+1] = [-1]*3
                        elif streak[1]>=4:
                            ans += c
                            puzzle[i][j] = -1
                    else:
                        streak[0] = c
                        streak[1] = 1
            for i, row in enumerate(puzzle[::-1]):
                if i==H-1:
                    break
                for j, c in enumerate(row):
                    if c==-1:
                        for h in range(H-i-1):
                            if puzzle[(H-i-1)-h-1][j]!=-1:
                                puzzle[-i-1][j] = puzzle[(H-i-1)-h-1][j]
                                puzzle[(H-i-1)-h-1][j] = -1
                                break
            if flg:
                print(ans)
                break

solve()

Solution (Python):

while True:
    h = int(input())
    if h==0:
        break
    puyo = [list(map(int, input().split())) for _ in range(h)]

    p = 0
    fin = 0
    turn = 1
    while fin==0:
        
        fin = 1
        for i in range(h):
            cnt = 1
            for j in range(1, 5):
                if puyo[i][j-1] == puyo[i][j] and puyo[i][j]>0:
                    cnt += 1
                else:
                    if cnt>=3:
                        p += cnt * puyo[i][j-1]
                        for k in range(cnt):
                            puyo[i][j-k-1] = -1
                            fin = 0
                    cnt = 1
                if j==4:
                    if cnt>=3:
                        p += cnt * puyo[i][j-1]
                        for k in range(cnt):
                            puyo[i][j-k] = -1
                            fin = 0
        
        
        for i in range(5):
            d_fin = 0
            while d_fin==0:
                d_fin = 1
                for j in range(h-1, 0, -1):
                    if puyo[j][i]==-1 and puyo[j-1][i]>0:
                        puyo[j][i] = puyo[j-1][i]
                        puyo[j-1][i] = -1
                        d_fin = 0
        
        turn += 1
    print(p)

Solution (Python):

import sys
import math
import string
import collections
import fractions
import random
from operator import itemgetter
import itertools
from collections import deque
import copy
import heapq
import bisect

MOD = 10 ** 9 + 7
INF = 10 ** 18
input = lambda: sys.stdin.readline().strip()

sys.setrecursionlimit(10 ** 8)

H = int(input())
while H != 0:
    table = [list(map(int, input().split())) for _ in range(H)]
    prev_ans = -1
    ans = 0
    while ans != prev_ans:
        prev_ans = ans
        for i in range(H):
            for j in range(3):
                if table[i][j] != -1:
                    if table[i][j] == table[i][j + 1] == table[i][j + 2]:
                        for l in range(j + 2, 5):
                            if table[i][j] != table[i][l]:
                                ans += (l - j) * table[i][j]
                                for k in range(j, l):
                                    table[i][k] = -1
                                break
                            elif l == 4:
                                ans += (l - j + 1) * table[i][j]
                                for k in range(j, 5):
                                    table[i][k] = -1
                                break
        for i in range(H - 2, -1, -1):
            for j in range(5):
                if table[i][j] != -1:
                    if table[i + 1][j] == -1:
                        for l in range(i + 1, H):
                            if table[l][j] != -1:
                                table[l - 1][j] = table[i][j]
                                for k in range(i, l - 1):
                                    table[k][j] = -1
                                break
                            elif l == H - 1:
                                table[l][j] = table[i][j]
                                table[i][j] = -1
                                break

    print(ans)
    H = int(input())