N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모든 나라는 1×1 크기이기 때문에, 모든 국경선은 정사각형 형태이다.
오늘부터 인구 이동이 시작되는 날이다.
인구 이동은 하루 동안 다음과 같이 진행되고, 더 이상 아래 방법에 의해 인구 이동이 없을 때까지 지속된다.
각 나라의 인구수가 주어졌을 때, 인구 이동이 며칠 동안 발생하는지 구하는 프로그램을 작성하시오.
# 16234
import sys
input = lambda: sys.stdin.readline().strip()
# 1. 두 나라의 인구 차이가 L명 이상, R명 이하라면 두 나라가 공유하는 국경선을 하루 동안 연다
# 2. 열어야 하는 국경선이 모두 열린다면, 인구 이동을 시작한다.
# 3. 연합을 이루고 있는 각 칸의 인구수는 (연합의 인구수) // (연합을 이루고 있는 칸의 개수)가 된다.
# 4. 연합을 해체하고, 모든 국경선을 닫는다.
# 5. 인구 이동이 발생할 때 까지 과정을 반복한다
from collections import deque
n, l, r = map(int, input().split())
arr = [list(map(int, input().split())) for _ in range(n)]
graph = []
dx, dy = [-1, 0, 1, 0], [0, 1, 0, -1]
def open():
global n, l, r, arr, graph
graph = []
check = False
for i in range(n):
graph.append([])
for j in range(n):
graph[i].append([])
if j < n-1 and l <= abs(arr[i][j] - arr[i][j+1]) <= r:
graph[i][j].append((i, j+1))
check = True
if j > 0 and l <= abs(arr[i][j] - arr[i][j-1]) <= r:
graph[i][j].append((i, j-1))
check = True
if i < n-1 and l <= abs(arr[i][j] - arr[i+1][j]) <= r:
graph[i][j].append((i+1, j))
check = True
if i > 0 and l <= abs(arr[i][j] - arr[i-1][j]) <= r:
graph[i][j].append((i-1, j))
check = True
return check
def bfs():
global n, arr, graph
visited = [[False] * n for _ in range(n)]
for i in range(n):
for j in range(n):
if visited[i][j]:
continue
num, people = 1, arr[i][j]
country = [(i, j)]
queue = deque()
queue.append((i, j))
visited[i][j] = True
while queue:
x, y = queue.popleft()
for nx, ny in graph[x][y]:
if visited[nx][ny]:
continue
queue.append((nx, ny))
num += 1
people += arr[nx][ny]
country.append((nx, ny))
visited[nx][ny] = True
people_per_country = people // num
for x, y in country:
arr[x][y] = people_per_country
day = 0
while open():
bfs()
day += 1
print(day)