Escaping the Barracks

Find the minimum level needed to walk from (0,0) to (n-1,m-1) on an n by m grid, using at most one jump that skips over exactly one block in a straight line.

Medium5Binary searchBFSGraphArrayInterviewNo attempts yetTime limit1sMemory limit256 MB

Problem

Giyun likes a game about escaping from the army. To finish the game he has to cross the barracks and get out. For the sake of discipline the barracks is always a rectangle of height nn and width mm.

Giyun starts on block (0,0)(0, 0) in the top left corner and has to reach block (n1,m1)(n-1, m-1) in the bottom right corner, moving only up, down, left, and right. He may never leave the barracks while moving, and he must step on block (0,0)(0, 0) and on block (n1,m1)(n-1, m-1).

Every block has a level requirement. If the number written on a block is 33, Giyun needs level 33 or higher to step on that block.

Giyun can use the air force's special equipment once per game. The equipment carries him from the block he is standing on over one block in a single direction, and he lands on the block two steps away in that direction. He does not step on the block he passes over, so its level requirement does not apply. Two conditions hold.

  1. He cannot change direction in the middle of the jump.
  2. The block he lands on has to be inside the barracks.

Find the lowest level Giyun needs in order to escape the barracks.

Input

The first line contains the height nn and the width mm of the barracks. (1n,m1001 \le n, m \le 100)

Each of the next nn lines contains mm level requirements, given from the top row down. Every level requirement kk satisfies 0k1090 \le k \le 10^9.

Output

Print the lowest level Giyun has to reach in order to escape the barracks.