Array Escape
InterviewTime limit2sMemory limit256 MB
Find the cheapest right-and-down path through a square grid where stepping to a higher or equal neighbor costs the raises needed to exceed it.
- Level
Easy3 of 10
- Topics
- Dynamic programming, Shortest path, Matrix
- Solved
- No attempts yet
Problem
Sangsu owns a two dimensional array of size . Here is a natural number that is at least 2, and every element of the array is an integer between 1 and 222.
Seunghyeon saw Sangsu playing with the array, burned with envy, and locked Sangsu inside . Seunghyeon still had a little conscience left, so he built an exit at and told Sangsu about it.

[Figure 1] When , Sangsu stands on and the exit is at .
Sangsu wants to reach the exit at as fast as possible. Suppose Sangsu stands on . To follow a shortest route, he moves under the conditions below.
- If , he jumps only to or to .
- If and , he jumps only to .
- If and , he jumps only to .
- If , he walks straight out through the exit.

[Figure 2] Suppose . The arrow marked (ㄱ) satisfies condition 1, the arrow marked (ㄴ) satisfies condition 2, and the arrow marked (ㄷ) satisfies condition 3.
A jump carries one more restriction. For Sangsu to jump from to , the values must satisfy . Sangsu felt that no route could keep this condition. Luckily, before Seunghyeon locked him in, Sangsu had built a button on every element of the array, and pressing a button raises that element by 1. (Sangsu can press only the button of the element he stands on.) Thanks to those buttons, Sangsu can always escape the array.

[Figure 3] Suppose . Since , Sangsu can jump from to . To jump from to instead, he presses the button on twice so that becomes 7.
Each button press costs 1 won. Sangsu wants to escape the array while spending as little money as possible. Help Sangsu.
Input
The first line contains . ()
The next lines follow. The -th of them () contains the numbers in order, separated by spaces.
Output
Print the minimum cost in won that Sangsu has to spend to escape the array.
Hint
In the first example, Sangsu can escape along the route drawn below.

This route spends 2 won on and 1 won on , for a total of 3 won, and that total is the minimum.