Question
The Descent of the Mountain Grid

In the mystical land of Numora, there lies a grand Mountain of Paths, made up of square stones arranged neatly in an n × n grid.

Each stone has an energy value — some positive, some negative.

You, the Seeker of Balance, must descend from the top row of the mountain to the bottom row, collecting the least possible total energy along your way.

But there’s a rule:

  • You can only step one row down at a time.

  • From your current stone at position (row, col), you can move:

    • Straight down(row + 1, col)

    • Diagonally left(row + 1, col - 1)

    • Diagonally right(row + 1, col + 1)

You may begin your descent from any stone in the first row.

Your quest:

Find the minimum total energy that can be collected by following any valid path from the top to the bottom of the mountain.

Input
The first line of the input contains a single integer n, representing the dimensions of the grid.
The next n lines each contain n space-separated integers, with the ith line representing elements in the ith row of the grid.
Output
Return a single integer — the minimum total energy you can collect on your descent.
Example
Input
3
1 2 3
4 5 6
7 8 9

Output
12

Explanation
The path is: 1 → 4 → 7, with a total sum of 12.

Online