import sys
input = sys.stdin.readline
from collections import deque
n , m = map(int, input().split())
board = [list(map(int, input().split())) for _ in range(n)]
dx = [1 , 0 , -1 , 0]
dy = [0 , 1 , 0 , -1]
point = 0
def gravity(board):
for j in range(n):
for i in range(n - 2 , -1 , -1):
if board[i][j] >= 0 and board[i + 1][j] == -2:
dropped = 0
for k in range(i + 1 , n):
if board[k][j] >= -1:
board[k - 1][j] = board[i][j]
board[i][j] = -2
dropped = 1
break
if not dropped:
board[n - 1][j] = board[i][j]
board[i][j] = -2
return board
def rotate_reverseClockwise(board):
rotated_board = [[0 for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
rotated_board[n - 1 - j][i] = board[i][j]
return rotated_board
def simulate(board):
groups = []
for num in range(1 , m + 1):
queue = deque()
visited = [[False] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if not visited[i][j] and board[i][j] == num:
totalBlock , rainbowBlock = 1 , 0
visited[i][j] = True
queue.append([i , j , num])
while queue:
[y , x , num] = queue.popleft()
for k in range(4):
ny = y + dy[k]
nx = x + dx[k]
if ny < 0 or nx < 0 or ny > n - 1 or nx > n - 1:
continue
if not visited[ny][nx] and board[ny][nx] == num:
totalBlock += 1
visited[ny][nx] = True
queue.append([ny , nx , num])
elif not visited[ny][nx] and board[ny][nx] == 0:
totalBlock += 1
rainbowBlock += 1
visited[ny][nx] = True
queue.append([ny , nx , num])
if totalBlock >= 2:
groups.append([totalBlock , rainbowBlock , i , j , num])
groups = sorted(groups , key = lambda x : (-x[0] , -x[1] , -x[2] , -x[3]))
return groups
while True:
groups = simulate(board)
if groups:
cy , cx , num = groups[0][2] , groups[0][3] , groups[0][4]
point += (groups[0][0] ** 2)
delete_visited = [[False] * n for _ in range(n)]
delete_visited[cy][cx] = True
board[cy][cx] = -2
queue = deque()
queue.append([cy , cx , num])
while queue:
y , x , num = queue.popleft()
for i in range(4):
ny = y + dy[i]
nx = x + dx[i]
if ny < 0 or nx < 0 or ny > n - 1 or nx > n - 1:
continue
if not delete_visited[ny][nx] and (board[ny][nx] == num or board[ny][nx] == 0):
board[ny][nx] = -2
delete_visited[ny][nx] = True
queue.append([ny , nx , num])
board = gravity(board)
board = rotate_reverseClockwise(board)
board = gravity(board)
else:
break
print(point)