#P11593. Uolevi's Frozen Lake

    ID: 13687 Type: Default 1000ms 256MiB

Uolevi's Frozen Lake

Uolevi's Frozen Lake

Uolevi is on a frozen lake which is divided into an (n\times m) grid. Each cell initially holds a coin. Moreover, each cell ( (i,j) ) has a capacity (A_{i,j}) which is the maximum number of coins the ice below it can support.

Uolevi can move one cell at a time in the four cardinal directions (up, down, left, right) without leaving the grid. If the cell he is currently on still has its coin, he may choose to pick it up. However, every time he moves from his current cell to an adjacent cell, he must ensure that the combined number of coins he is carrying and the coin that still remains in the target cell (if it has not been collected) does not exceed the target cell’s capacity. In other words, if he is carrying (c) coins and the target cell still has its coin, then it must hold that:

[ c+1 \le A_{target} ]

If the coin in the target cell has already been collected, then the condition is (c \le A_{target}).

Uolevi’s journey must start at a cell on the boundary of the grid and end at a cell on the boundary. He wants to know the maximum number of coins he can collect along such a path.

Note: Although Uolevi may choose not to pick up a coin in a cell (even if available) to satisfy future movement constraints, each cell’s coin can only be collected at most once.

inputFormat

The first line contains two integers (n) and (m) (the number of rows and columns). The following (n) lines each contain (m) integers. The (j)th integer in the (i)th line (1-indexed) is (A_{i,j}), the capacity of the cell at row (i) and column (j). All cells initially contain one coin.

outputFormat

Output a single integer, the maximum number of coins Uolevi can collect while starting at and ending on a boundary cell following the rules.

sample

2 2
1 2
2 1
2