import sys
from collections import deque
sys.stdin = open("input.txt")
def get_rotate_data(graph):
result_list = []
for i in range(3):
for j in range(3):
for d in range(3):
new_graph = rotate(i, j, d, graph)
point, new_graph = get_point(new_graph)
result_list.append([point, d, i, j, new_graph])
return result_list
def rotate(x, y, d, graph):
new_graph = [[0] * 5 for _ in range(5)]
if d == 0:
for i in range(3):
for j in range(3):
new_graph[j + x][2 - i + y] = graph[x + i][y + j]
if d == 1:
for i in range(3):
for j in range(3):
new_graph[2 - i + x][2 - j + y] = graph[x + i][y + j]
if d == 2:
for i in range(3):
for j in range(3):
new_graph[2 - j + x][i + y] = graph[x + i][y + j]
for i in range(5):
for j in range(5):
if new_graph[i][j] == 0:
new_graph[i][j] = graph[i][j]
return new_graph
def get_point(graph):
visited = [[False] * 5 for _ in range(5)]
total_point = 0
for i in range(5):
for j in range(5):
if not visited[i][j]:
point, graph = bfs(i, j, graph, visited)
total_point += point
return total_point, graph
def bfs(r, c, graph, visited):
target = graph[r][c]
dq = deque()
dq.append([r, c])
visited[r][c] = True
nodes = []
nodes.append([r, c])
while dq:
x, y = dq.popleft()
for dx, dy in dirs:
nx, ny = x + dx, y + dy
if in_range(nx, ny) and not visited[nx][ny] and graph[nx][ny] == target:
dq.append([nx, ny])
nodes.append([nx, ny])
visited[nx][ny] = True
if len(nodes) >= 3:
for x, y in nodes:
graph[x][y] = 0
point = len(nodes) if len(nodes) >= 3 else 0
return point, graph
def select_best_graph(result_list):
result_list.sort(key=lambda x: (-x[0], x[1], x[3], x[2]))
best_result = result_list[0]
return best_result[0], best_result[4]
def add_new_number(graph):
global num_idx
for col in range(5):
for row in range(4, -1, -1):
if graph[row][col] == 0:
graph[row][col] = nums[num_idx]
num_idx += 1
return graph
def get_additional_points(graph):
additional_point = 0
point, graph = get_point(graph)
if point > 0:
graph = add_new_number(graph)
additional_point += point
while point > 0:
point, graph = get_point(graph)
if point > 0:
graph = add_new_number(graph)
additional_point += point
return additional_point, graph
def in_range(x, y):
return 0 <= x < 5 and 0 <= y < 5
K, M = map(int, sys.stdin.readline().split())
maps = []
nums = []
num_idx = 0
point_list = []
dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]
for _ in range(5):
maps.append(list(map(int, sys.stdin.readline().split())))
nums = list(map(int, sys.stdin.readline().split()))
for _ in range(K):
total_point = 0
rotate_result_list = get_rotate_data(maps)
point, maps = select_best_graph(rotate_result_list)
if point == 0:
break
total_point += point
maps = add_new_number(maps)
point, maps = get_additional_points(maps)
total_point += point
point_list.append(total_point)
print(*point_list)