Problem:


Score : 700 points

Problem Statement

Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to right); and so on until the last row, whose viewers are denoted by N^2-N+1,\dots, N^2.

At the end of the movie, the viewers go out of the cinema in a certain order: the i-th viewer leaving her seat is the one denoted by the number P_i. The viewer P_{i+1} waits until viewer P_i has left the cinema before leaving her seat.
To exit from the cinema, a viewer must move from seat to seat until she exits the square of seats (any side of the square is a valid exit). A viewer can move from a seat to one of its 4 adjacent seats (same row or same column).
While leaving the cinema, it might be that a certain viewer x goes through a seat currently occupied by viewer y; in that case viewer y will hate viewer x forever. Each viewer chooses the way that minimizes the number of viewers that will hate her forever.

Compute the number of pairs of viewers (x, y) such that y will hate x forever.

Constraints

2 \le N \le 500

The sequence P_1, P_2, \dots, P_{N^2} is a permutation of \{1, 2, \dots, N^2\}.

Input

The input is given from Standard Input in the format

N
P_1 P_2 \cdots P_{N^2}

Output

If ans is the number of pairs of viewers described in the statement, you should print on Standard Output

ans

Sample Input 1

3
1 3 7 9 5 4 8 6 2

Sample Output 1

1

Before the end of the movie, the viewers are arranged in the cinema as follows:

1 2 3
4 5 6
7 8 9

The first four viewers leaving the cinema (1, 3, 7, 9) can leave the cinema without going through any seat, so they will not be hated by anybody.

Then, viewer 5 must go through one of the seats where viewers 2, 4, 6, 8 are currently seated while leaving the cinema; hence he will be hated by at least one of those viewers.

Finally the remaining viewers can leave the cinema (in the order 4, 8, 6, 2) without going through any occupied seat (actually, they can leave the cinema without going through any seat at all).

Sample Input 2

4
6 7 1 4 13 16 10 9 5 11 12 14 15 2 3 8

Sample Output 2

3

Sample Input 3

6
11 21 35 22 7 36 27 34 8 20 15 13 16 1 24 3 2 17 26 9 18 32 31 23 19 14 4 25 10 29 28 33 12 6 5 30

Sample Output 3

11



Sample input:
3
1 3 7 9 5 4 8 6 2


Sample output:
1

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
p = list(map(int,input().split()))

links = [[] for _ in range(1 + n**2)]
for i in range(n):
    for j in range(n):
        x = i*n+j + 1
        if(i!=0):
            links[x].append(x-n)
        if(i!=n-1):
            links[x].append(x+n)
        if(j!=0):
            links[x].append(x-1)
        if(j!=n-1):
            links[x].append(x+1)
        if(i==0)|(i==n-1)|(j==0)|(j==n-1):
            links[x].append(0)

sit = [1] * (1+n**2)
sit[0] = 0

def dfs(links,start,goal,m):
    cost = [-1]*m
    stack = [[start],[]]
    cost[start] = 0
    for depth in range(n+10):
        while(stack[depth%2]):
            now = stack[depth%2].pop()
            for y in links[now]:
                if(cost[y] == -1):
                    cost[y] = depth + sit[y]
                    stack[cost[y]%2].append(y)

        if(cost[goal] != -1):
            return cost[goal]

ans = 0
for x in p:
    sit[x] = 0
    ans += dfs(links,x,0,n**2+1)

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#################################3
#################################3
#################################3
#################################3


def read(data_type=int, container_type=list):
    return container_type(data_type(x) for x in input().split())


import collections

N, = read()
P = read()


def get_rc(x):
    return x // N, x % N


grid = [[True] * N for _ in range(N)]


def nei(r, c):
    for dr, dc in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
        r2 = r + dr
        c2 = c + dc
        if 0 <= r2 < N and 0 <= c2 < N:
            yield (r2, c2)


def find_min_dist(r, c):
    visited_dist = {(r, c): 0}
    q = collections.deque([(r, c)])
    while q:
        r, c = q.popleft()
        if r == 0 or r == N - 1 or c == 0 or c == N - 1:
            return visited_dist[(r, c)]
        for r2, c2 in nei(r, c):
            if (r2, c2) not in visited_dist:
                if grid[r2][c2]:
                    visited_dist[(r2, c2)] = 1 + visited_dist[r, c]
                    q.append((r2, c2))
                else:
                    visited_dist[r2, c2] = visited_dist[r, c]
                    q.appendleft((r2, c2))


sol = 0
for x in P:
    r, c = get_rc(x - 1)
    grid[r][c] = False
    sol += find_min_dist(r, c)

print(sol)

#################################3
#################################3
#################################3
#################################3

Submission status: Time Limit Exceeded

Solution code:
import collections
import itertools


class Cell(object):

    def __init__(self):
        self.value = None
        self.exist = 1
        self.neighbors = []


def main():
    N = int(input())
    cells = [[Cell() for _ in range(N)] for _ in range(N)]
    queue = collections.deque()
    count = 0

    for x, y in itertools.product(range(N), repeat=2):
        c = cells[y][x]

        if x == 0:
            c.value = 0
        else:
            c.neighbors.append(cells[y][x - 1])

        if x == N - 1:
            c.value = 0
        else:
            c.neighbors.append(cells[y][x + 1])

        if y == 0:
            c.value = 0
        else:
            c.neighbors.append(cells[y - 1][x])

        if y == N - 1:
            c.value = 0
        else:
            c.neighbors.append(cells[y + 1][x])

        if c.value == 0:
            queue.append(c)

    while len(queue) != 0:
        c = queue.popleft()

        for n in c.neighbors:
            if n.value is None:
                n.value = c.value + 1
                queue.append(n)

    for i in map(int, input().split()):
        x, y = divmod(i - 1, N)
        count += cells[y][x].value

        cells[y][x].exist = 0

        queue.append(cells[y][x])

        while len(queue) != 0:
            c = queue.popleft()
            v = c.value + c.exist

            for n in c.neighbors:
                if n.value > v:
                    n.value = v
                    queue.append(n)

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N, = map(int, input().split())
R = [0] * (N**2+1)
V = [0] * (N**2+1)
X = list(map(int, input().split()))
for ai in range(N**2):
    i, j = divmod(ai, N)
    R[ai+1] = min([i, N-i-1, j, N-j-1])

r = 0
for a in X:
    r += R[a]
    V[a] = 1
    stack=[a]
    while stack:
        v = stack.pop()
        i, j = divmod(v-1, N)
        ccs = []
        if v>N:
            ccs.append(v-N)
        if v<N**2+1-N:
            ccs.append(v+N)
        if v%N:
            ccs.append(v+1)
        if v%N!=1:
            ccs.append(v-1)
        for u in ccs:
            if R[v]>=R[u] or ((1-V[v]) and R[v]+1 >= R[u]):
                continue
            R[u] -= 1
            stack.append(u)
print(r)

Submission status: Time Limit Exceeded

Solution code:
import collections
import itertools


class Cell(object):

    def __init__(self):
        self.value = None
        self.exist = 1
        self.neighbors = []


def main():
    N = int(input())
    cells = [[Cell() for _ in range(N)] for _ in range(N)]
    queue = collections.deque()
    count = 0

    for x, y in itertools.product(range(N), repeat=2):
        c = cells[y][x]

        if x == 0:
            c.value = 0
        else:
            c.neighbors.append(cells[y][x - 1])

        if x == N - 1:
            c.value = 0
        else:
            c.neighbors.append(cells[y][x + 1])

        if y == 0:
            c.value = 0
        else:
            c.neighbors.append(cells[y - 1][x])

        if y == N - 1:
            c.value = 0
        else:
            c.neighbors.append(cells[y + 1][x])

        if c.value == 0:
            queue.append(c)

    while len(queue) != 0:
        c = queue.popleft()

        for n in c.neighbors:
            if n.value is None:
                n.value = c.value + 1
                queue.append(n)

    queue = collections.deque()

    for i in map(int, input().split()):
        x, y = divmod(i - 1, N)
        count += cells[y][x].value

        cells[y][x].value -= 1
        cells[y][x].exist = 0

        queue.append(cells[y][x])

        while len(queue) != 0:
            c = queue.popleft()

            for n in c.neighbors:
                if n.value > c.value + n.exist:
                    n.value = c.value + n.exist
                    queue.append(n)

    print(count)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N, = map(int, input().split())
R = [0] * (N**2+1)
V = [0] * (N**2+1)
X = list(map(int, input().split()))
for ai in range(N**2):
    i, j = divmod(ai, N)
    R[ai+1] = min([i, N-i-1, j, N-j-1])
#print(R)

r = 0
for a in X:
    r += R[a]
    V[a] = 1
    stack=[a]
    vs = set([a])
    while stack:
        v = stack.pop()
        i, j = divmod(v-1, N)
        ccs = []
        if v>N:
            ccs.append(v-N)
        if v<N**2+1-N:
            ccs.append(v+N)
        if v%N:
            ccs.append(v+1)
        if v%N!=1:
            ccs.append(v-1)
        for u in ccs:
            if u in vs:
                continue
            if V[v] and R[v] >= R[u]:
                continue
            if (1-V[v]) and R[v] +1 >= R[u]:
                continue
            R[u] -= 1
            vs.add(u)
            stack.append(u)
print(r)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = list(map(int,input().split()))
g = [[0]*n for i in range(n)]
a = [[1]*n for i in range(n)]
ans = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for i in range(1,n-1):
    for j in range(1,n-1):
        g[i][j] = min(i,j,n-i-1,n-j-1)
for i in p:
    y = (i-1)//n
    x = (i-1)%n
    ans += g[y][x]
    dq = deque([(y,x)])
    a[y][x] = 0
    while dq:
        y,x = dq.popleft()
        t = a[y][x]
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]+t:
                g[y1][x1] = g[y][x]+t
                dq.append((y1,x1))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int16)

    ans = 0

    for pi in range(n * n):
        i, j = divmod(ppp[pi], n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [(0, 0)] * nsq
        l, r = 0, 0
        for mi in range(4):
            ni = i + MOVES[mi]
            if seats[ni] > res:
                deque[r] = (res, ni)
                r += 1

        while l != r:
            val, j = deque[l]
            # print(val, j, deque)
            l = (l + 1) % nsq
            if seats[j] <= val:
                continue
            seats[j] = val

            if is_seated[j]:
                val += 1
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        deque[r] = (val, nj)
                        r = (r + 1) % nsq
            else:
                for mi in range(4):
                    nj = j + MOVES[mi]
                    if seats[nj] > val:
                        l = (l - 1) % nsq
                        deque[l] = (val, nj)

        # print(ppp[pi] + 1, i, ans)
        # print(seats.reshape((n2, n2)))
        # print(is_seated.reshape((n2, n2)))

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64) - 1

# n = 500
# ppp = np.random.permutation(n * n).astype(np.int64)
# print(ppp)

print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = list(map(int,input().split()))
g = [[0]*n for i in range(n)]
a = [[1]*n for i in range(n)]
ans = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for i in range(1,n-1):
    for j in range(1,n-1):
        g[i][j] = min(i,j,n-i-1,n-j-1)
# print(g)
for i in p:
    y = (i-1)//n
    x = (i-1)%n
    ans += g[y][x]
    dq = deque([(y,x)])
    a[y][x] = 0
    while dq:
        y,x = dq.popleft()
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]+1 and a[y][x] == 1:
                g[y1][x1] = g[y][x] + 1
                dq.append((y1,x1))
            elif g[y1][x1] > g[y][x] and a[y][x] == 0:
                g[y1][x1] = g[y][x]
                dq.appendleft((y1,x1))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = list(map(int,input().split()))
g = [[0]*n for i in range(n)]
a = [[1]*n for i in range(n)]
ans = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for i in range(1,n-1):
    for j in range(1,n-1):
        g[i][j] = min(i,j,n-i-1,n-j-1)
# print(g)
for i in p:
    y = (i-1)//n
    x = (i-1)%n
    ans += g[y][x]
    dq = deque([(y,x)])
    a[y][x] = 0
    while dq:
        y,x = dq.popleft()
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]+1 and a[y][x] == 1:
                g[y1][x1] = g[y][x] + 1
                dq.append((y1,x1))
            elif g[y1][x1] > g[y][x] and a[y][x] == 0:
                g[y1][x1] = g[y][x]
                dq.append((y1,x1))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int16)

    ans = 0

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [(0, 0)] * nsq
        l, r = 0, 4
        for dj in MOVES:
            deque[l] = (res, i + dj)
            l += 1
        l = 0

        while l != r:
            val, j = deque[l]
            # print(val, j, deque[l:r] if l >= 0 else deque[l:] + deque[:r])
            l = (l + 1) % nsq
            if seats[j] <= val:
                continue
            seats[j] = val

            if is_seated[j]:
                val += 1
                for dj in MOVES:
                    nj = j + dj
                    if seats[nj] > val:
                        deque[r] = (val, nj)
                        r = (r + 1) % nsq
            else:
                for dj in MOVES:
                    nj = j + dj
                    if seats[nj] > val:
                        l = (l - 1) % nsq
                        deque[l] = (val, nj)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
n = int(input())
p = list(map(int,input().split()))
g = [[0]*n for i in range(n)]
a = [[1]*n for i in range(n)]
ans = 0
opt = [(1,0),(0,1),(-1,0),(0,-1)]
for i in range(1,n-1):
    for j in range(1+i-1,n-i):
        for k in range(i,n-i):
            g[j][k] += 1
for i in p:
    y = (i-1)//n
    x = (i-1)%n
    ans += g[y][x]
    dq = deque([(y,x)])
    a[y][x] = 0
    while dq:
        y,x = dq.popleft()
        for j in opt:
            y1,x1 = y+j[0],x+j[1]
            if y1<0 or x1<0 or y1>=n or x1>=n:
                continue
            if g[y1][x1] > g[y][x]+1 and a[y][x] == 1:
                g[y1][x1] = g[y][x] + 1
                dq.append((y1,x1))
            elif g[y1][x1] > g[y][x] and a[y][x] == 0:
                g[y1][x1] = g[y][x]
                dq.append((y1,x1))
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int16)

    ans = 0

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [(0, 0)] * nsq
        deque[0] = (res, i)
        l, r = 0, 1
        seats[i] += 1  # dummy for first loop
        updated = set()

        while l != r:
            val, j = deque[l]
            # print(val, j, deque[l:r] if l >= 0 else deque[l:] + deque[:r])
            l = (l + 1) % nsq
            if j in updated:
                continue
            updated.add(j)
            seats[j] = val

            if is_seated[j]:
                val += 1
                for dj in MOVES:
                    nj = j + dj
                    if seats[nj] > val and nj not in updated:
                        deque[r] = (val, nj)
                        r = (r + 1) % nsq
            else:
                for dj in MOVES:
                    nj = j + dj
                    if seats[nj] > val and nj not in updated:
                        l = (l - 1) % nsq
                        deque[l] = (val, nj)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int16)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int16)

    ans = 0

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [(0, 0)] * nsq
        deque[0] = (res, i)
        l, r = 0, 1
        seats[i] += 1  # dummy for first loop

        while l != r:
            val, j = deque[l]
            # print(val, j, deque[l:r] if l >= 0 else deque[l:] + deque[:r])
            l = (l + 1) % nsq
            if seats[j] <= val:
                continue
            seats[j] = val

            if is_seated[j]:
                val += 1
                for dj in MOVES:
                    nj = j + dj
                    if seats[nj] > val:
                        deque[r] = (val, nj)
                        r = (r + 1) % nsq
            else:
                for dj in MOVES:
                    nj = j + dj
                    if seats[nj] > val:
                        l = (l - 1) % nsq
                        deque[l] = (val, nj)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

from numba import njit, int64


@njit(int64(int64, int64[:]), cache=True)
def solve(n, ppp):
    n2 = n + 2
    nsq = n2 * n2
    seats = np.zeros(nsq, dtype=np.int64)
    is_seated = np.zeros(nsq, dtype=np.int8)
    for i in range(n):
        ud = min(i, n - 1 - i)
        ri = (i + 1) * n2
        for j in range(n):
            ij = ri + j + 1
            seats[ij] = min(ud, j, n - 1 - j)
            is_seated[ij] = 1

    MOVES = np.array([-n2, -1, 1, n2], dtype=np.int64)

    ans = 0

    for p in ppp:
        i, j = divmod(p - 1, n)
        i = (i + 1) * n2 + j + 1
        res = seats[i]
        ans += res
        is_seated[i] = 0

        deque = [(0, 0)] * nsq
        deque[0] = (res, i)
        l, r = 0, 1

        while l != r:
            val, j = deque[l]
            # print(val, j, deque[l:r] if l >= 0 else deque[l:] + deque[:r])
            l = (l + 1) % nsq
            seats[j] = val

            if is_seated[j]:
                val += 1
                for dj in MOVES:
                    nj = j + dj
                    if seats[nj] > val:
                        deque[r] = (val, nj)
                        r = (r + 1) % nsq
            else:
                for dj in MOVES:
                    nj = j + dj
                    if seats[nj] > val:
                        l = (l - 1) % nsq
                        deque[l] = (val, nj)

    return ans


n = int(sys.stdin.buffer.readline())
ppp = np.array(list(map(int, sys.stdin.buffer.read().split())), dtype=np.int64)
print(solve(n, ppp))

# solve.inspect_types()
# bfs.inspect_types()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
p = list(map(int, input().split()))

d = [[None]*n for _ in range(n)]
for i in range(n):
    for j in range(n):
        d[i][j] = min(i, n-1-i, j, n-1-j)
vacant = [[False]*n for _ in range(n)]
def sub(x,y):
    v = d[x][y]
    q = [(v, x, y)]
    dx = [0,1,0,-1]
    dy = [1,0,-1,0]
    while q:
        v,i,j = q.pop()
        for xx, yy in zip(dx,dy):
            ii = i+xx
            jj = j+yy
            if ii<0 or jj<0 or ii>=n or jj>=n:
                continue
            if d[ii][jj]>v:
                d[ii][jj] = v
                nv = v+1 if not vacant[ii][jj] else v
                q.append((nv, ii, jj))
ans = 0
for v in p:
    v -= 1
    x,y = v//n, v%n
    ans += d[x][y]
#     print(v, d[x][y], d)
    sub(x,y)
    vacant[x][y] = True
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
from scipy.sparse.csgraph import shortest_path

def main():
    N=int(input())
    P=list(map(lambda x:int(x)-1,input().split()))

    grid=np.zeros((N,N))

    graph=[]

    cost=N*N

    for i in range(N*N):
        temp=[0 for _ in range(N*N)]
        if (i+1)%N==0:
            temp[i-1]=cost
            if i-N>=0:
                temp[i-N]=cost
            if i+N<=N*N-1:
                temp[i+N]=cost
        elif (i%N)==0:
            temp[i+1]=cost
            if i-N>=0:
                temp[i-N]=cost
            if i+N<=N*N-1:
                temp[i+N]=cost
        elif i<=N-1:
            temp[i+N]=cost
            temp[i+1]=cost
            temp[i-1]=cost
        elif i>=N*N-N:
            temp[i-N]=cost
            temp[i+1]=cost
            temp[i-1]=cost
        else:
            temp[i+1]=cost
            temp[i-1]=cost
            temp[i+N]=cost
            temp[i-N]=cost
        graph.append(temp)

    graph=np.array(graph)

    res=0
    goal=[]
    for i in range(N):
        goal.append(i)
        if i==0 or i==N-1:
            for j in range(N):
                goal.append(i+j*N)
        else:
            goal.append(i + N * (N - 1))

    for p in P:
        if (p in goal):
            short=[0 for _ in range(N)]
            mini=0
        else:
            short=shortest_path(graph,indices=p,method="D")
            mini=2*10**5
            for g in goal:
                mini=min(mini,short[g])
        res+=mini//cost
        g_col=graph[:,p]
        g_col=np.where(g_col==cost,1,g_col)
        graph[:,p]=g_col


    print(int(res))

if __name__=="__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
from collections import deque
from scipy.sparse.csgraph import shortest_path

def main():
    N=int(input())
    P=list(map(lambda x:int(x)-1,input().split()))

    grid=np.zeros((N,N))

    graph=[]

    cost=N*N

    for i in range(N*N):
        temp=[0 for _ in range(N*N)]
        if (i+1)%N==0:
            temp[i-1]=cost
            if i-N>=0:
                temp[i-N]=cost
            if i+N<=N*N-1:
                temp[i+N]=cost
        elif (i%N)==0:
            temp[i+1]=cost
            if i-N>=0:
                temp[i-N]=cost
            if i+N<=N*N-1:
                temp[i+N]=cost
        elif i<=N-1:
            temp[i+N]=cost
            temp[i+1]=cost
            temp[i-1]=cost
        elif i>=N*N-N:
            temp[i-N]=cost
            temp[i+1]=cost
            temp[i-1]=cost
        else:
            temp[i+1]=cost
            temp[i-1]=cost
            temp[i+N]=cost
            temp[i-N]=cost
        graph.append(temp)

    graph=np.array(graph)

    res=0
    goal=[]
    for i in range(N):
        goal.append(i)
        if i==0 or i==N-1:
            for j in range(N):
                goal.append(i+j*N)
        else:
            goal.append(i + N * (N - 1))

    for p in P:
        short=shortest_path(graph,indices=p,method="D")
        mini=2*10**5
        for g in goal:
            mini=min(mini,short[g])
        res+=mini//cost
        g_col=graph[:,p]
        g_col=np.where(g_col==cost,1,g_col)
        graph[:,p]=g_col


    print(int(res))

if __name__=="__main__":
    main()