



import sys
from collections import deque
input = sys.stdin.readline
dx = (0, 1, 0, -1)
dy = (1, 0, -1, 0)
N, M = map(int, input().split())
board = [list(map(int, input().split())) for n in range(N)]
dice = [1, 6, 2, 5, 3, 4]
def MoveDice(direction):
global dice
a, b, c, d, e, f = dice
if direction == 0:
dice = [f, e, c, d, a, b]
elif direction == 1:
dice = [d, c, a, b, e, f]
elif direction == 2:
dice = [e, f, c, d, b, a]
elif direction == 3:
dice = [c, d, b, a, e, f]
def bfs(x, y, number):
global ans
queue = deque([]); queue.append((x, y))
visit = [[False]*N for n in range(N)]; visit[x][y] = True
while queue:
x, y = queue.popleft()
ans += number
for i in range(4):
nx, ny = x+dx[i], y+dy[i]
if 0<=nx<N and 0<=ny<N:
if not visit[nx][ny] and board[nx][ny] == number:
queue.append((nx, ny))
visit[nx][ny] = True
direction = 0
ans = 0
x, y = 0, 0
for m in range(M):
nx, ny = x+dx[direction], y+dy[direction]
if nx < 0 or nx >= N or ny < 0 or ny >= N: direction = (direction+2)%4
x += dx[direction]; y += dy[direction]
MoveDice(direction)
bfs(x, y, board[x][y])
if board[x][y] < dice[1]: direction = (direction+1)%4
elif board[x][y] > dice[1]: direction = (direction-1)%4
print(ans)