All problems

Problem 646

Cherry Pickup

Hard · 30 pts · Dynamic Programming, Matrix

Problem

An N × N grid holds 0 (empty), 1 (a cherry) or -1 (a thorn you cannot pass). Walk from the top-left to the bottom-right cell moving only right or down, then walk back to the top-left moving only left or up. Each cherry you pass is picked up once and the cell becomes empty. Find the most cherries you can collect, or 0 if there is no valid path. Model the round trip as two walkers going down at the same time; after k steps both are on the anti-diagonal r + c = k, so the state is (k, r1, r2).

Input

The first line contains N. Each of the next N lines contains N integers, each -1, 0 or 1.

Output

Print the maximum number of cherries.

Constraints

1 <= N <= 50; the top-left and bottom-right cells are not -1

Example input

3
0 1 -1
1 0 -1
1 1 1

Example output

5

Explanation

In the grid 0 1 -1 / 1 0 -1 / 1 1 1, go down the left side and along the bottom (picking 4 cherries), then come back through the middle and the top (picking the last 1). That collects all 5 cherries.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Stone Game II Next: Max Dot Product of Two Subsequences