n, m = map(int, input().split())
g = [list(map(int, input().split())) for _ in range(n)]
d = [0] * m
s = [0] * m
dx = [0, -1, -1, -1, 0, 1, 1, 1]
dy = [-1, -1, 0, 1, 1, 1, 0, -1]
du = [-1, -1, 1, 1]
dv = [-1, 1, -1, 1]
cloud = []
delcloud = []
cloud.append((n-1, 0))
cloud.append((n-1, 1))
cloud.append((n-2, 0))
cloud.append((n-2, 1))
def mul(u, v):
cnt = 0
for i in range(4):
nu, nv = u + du[i], v + dv[i]
if nu < 0 or nv < 0 or nu >= n or nv >= n:
continue
if g[nu][nv] != 0:
cnt += 1
g[u][v] += cnt
return g
def create(cloud, delcloud):
for i in range(n):
for j in range(n):
if (i, j) not in delcloud and g[i][j] >= 2:
cloud.append((i, j))
g[i][j] -= 2
for i in range(m):
delcloud.clear()
d[i], s[i] = map(int, input().split())
for u, v in cloud:
u, v = (u + dx[d[i]-1] * s[i]) % n, (v + dy[d[i]-1] * s[i]) % n
delcloud.append((u, v))
cloud.clear()
for u, v in delcloud:
g[u][v] += 1
for u, v in delcloud:
g = mul(u, v)
create(cloud, delcloud)
ans = 0
for i in range(n):
ans += sum(g[i])
print(ans)