You and an arbitrary number of friends are standing on a grid of baklava of size $$$N \times M$$$, all at coordinate $$$(0, 0)$$$.
Each piece of baklava at coordinate $$$(i, j)$$$ has a limited durability $$$K_{ij}$$$, meaning it can only be stepped on $$$K_{ij}$$$ times. The baklava pieces at $$$(0, 0)$$$ and $$$(N-1, M-1)$$$ both have infinite durability.
You and your friends walk through the baklava grid one by one. At any step, you may travel to a piece that is one step up, down, left, or right from your current piece, but you may not leave the grid. Given the durability across the baklava grid, at most how many friends can make it across to coordinate $$$(N-1, M-1)$$$ until the grid has become too deteriorated to allow anyone past?
Constraints:
$$$2 \leq N \leq 100$$$
$$$2 \leq M \leq 100$$$
$$$0 \leq K_{ij} \leq 100,000$$$
Two integers $$$N$$$, and $$$M$$$, on the first line.
$$$N$$$ lines follow, going from row index $$$i=0$$$ to $$$i=N-1$$$. For each line, $$$M$$$ values follow, going from value index $$$j=0$$$ to $$$j=M-1$$$, each one representing the durability $$$K_{ij}$$$.
Note that the values $$$K_{(0, 0)}$$$ and $$$K_{(N-1, M-1)}$$$ are not needed to solve the problem, as the pieces have infinite durability.
One integer representing the number of friends that can make it across.
2 2 0 1000 2000 0
3000