시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율
1 초 128 MB 2058 428 274 20.571%

문제

n×n짜리의 배열이 하나 있다. 이 배열의 (1, 1)에서 (n, n)까지 이동하려고 한다. 이동할 때는 상, 하, 좌, 우의 네 인접한 칸으로만 이동할 수 있다.

이와 같이 이동하다 보면, 배열에서 몇 개의 수를 거쳐서 이동하게 된다. 이동하기 위해 거쳐 간 수들 중 최대값과 최소값의 차이가 가장 작아지는 경우를 구하는 프로그램을 작성하시오.

입력

첫째 줄에 n(2≤n≤100)이 주어진다. 다음 n개의 줄에는 배열이 주어진다. 배열의 각 수는 0보다 크거나 같고, 200보다 작거나 같은 정수이다.

출력

첫째 줄에 (최대 - 최소)가 가장 작아질 때의 그 값을 출력한다.

예제 입력 1

5
1 1 3 6 8
1 2 2 5 5
4 4 0 3 3
8 0 2 3 4
4 3 0 2 1

예제 출력 1

2
W3sicHJvYmxlbV9pZCI6IjE5ODEiLCJwcm9ibGVtX2xhbmciOiIwIiwidGl0bGUiOiJcdWJjMzBcdWM1ZjRcdWM1ZDBcdWMxMWMgXHVjNzc0XHViM2Q5IiwiZGVzY3JpcHRpb24iOiI8cD5uJnRpbWVzO25cdWM5ZGNcdWI5YWNcdWM3NTggXHViYzMwXHVjNWY0XHVjNzc0IFx1ZDU1OFx1YjA5OCBcdWM3ODhcdWIyZTQuIFx1Yzc3NCBcdWJjMzBcdWM1ZjRcdWM3NTggKDEsIDEpXHVjNWQwXHVjMTFjIChuLCBuKVx1YWU0Y1x1YzljMCBcdWM3NzRcdWIzZDlcdWQ1NThcdWI4MjRcdWFjZTAgXHVkNTVjXHViMmU0LiBcdWM3NzRcdWIzZDlcdWQ1NjAgXHViNTRjXHViMjk0IFx1YzBjMSwgXHVkNTU4LCBcdWM4OGMsIFx1YzZiMFx1Yzc1OCBcdWIxMjQgXHVjNzc4XHVjODExXHVkNTVjIFx1Y2U3OFx1YzczY1x1Yjg1Y1x1YjljYyBcdWM3NzRcdWIzZDlcdWQ1N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