[Solution] Greedy Grid Moves CodeChef
Problem
Anya and Becky found an grid that contains distinct integers, and decided to play a game on it. The integer present at the intersection of the -th row and -th column is denoted .
They place a token at the top-left corner (cell ), and then take turns moving the token towards the bottom-right corner (cell ), each time moving the token one step right or down. Becky moves first.
Suppose the token is at position . Then,
- Becky can choose to move the token to either or .
- Anya, in her infinite
greedwisdom, will always move the token to whichever cell has the larger value. That is,- She will move the token to cell if
- She will move the token to cell if
Of course, the token must remain inside the grid at all times, so if they cannot move it down and if they cannot move it right.
Let be the maximum value the two encounter on their path from to . Becky would like to rein in Anya a bit, so please help her: if she makes her moves optimally, what is the minimum possible value of ?
Input Format
- The first line of input will contain a single integer , denoting the number of test cases.
- Each test case consists of multiple lines of input.
- The first line of each test case contains two space-separated integers and — the number of rows and columns of the grid.
- The next lines describe the grid. The -th of these lines contains space-separated integers .
Output Format
For each test case, output on a new line the minimum possible value of , if Becky chooses her moves optimally.
Explanation:
Test case : Since is the largest value in the grid, no matter what path is taken the maximum value is going to be .
Test case : Becky can move the token down in the first move, which forces Anya to move right on hers. This gives the path with a maximum of , which is the best possible.
Test case : The optimal path is , with a maximum of .
Note that if Anya had chosen to move down to when at , she could have forced the maximum to be . However, so she will never choose to do this.
No comments:
Post a Comment