You are given a matrix A containing N rows and M columns and an integer C.
Initially, all cells are assigned some value less or equal to C. A[i][j] is the value of the ith row and jth column.
Each second all cell's value is increased by 1 but it can increase maximum up to C after that value of A[i][j] is unchanged.
On the 0th second, you are at (1,1) cell and want to go to (N,M) cell.
At any point in time, you can jump to any adjacent cell. If you are at (i,j), then you can go to any of the adjacent cells, (i−1,j), (i+1,j), (i,j+1), and (i,j−1). You can move to the adjacent cells only on one condition :
You can move to any adjacent cell if and only if the value of the cell, where you are standing, is equal to the value of the adjacent cell and you can not go outside of the matrix
Note: Jump time is negligible
Your task is to determine the minimum time to reach (N,M) from the cell.
Input format
Output format
Print single integer minimum time to reach (N,M) cell.
Constraints
1≤N∗M≤3∗105
1≤C≤109
1≤A[i][j]≤C
after one second matrix became
3 | 3 |
2 | 3 |
now there is a path from (1, 1) to (2, 2).