Cornfield
InterviewTime limit1sMemory limit1024 MB
Given a grid of distinct values, repeatedly harvest the largest-valued cell reachable from the border through already harvested cells, and print the first K positions in order.
- Level
Medium4 of 10
- Topics
- Heap, Greedy, Simulation
- Solved
- No attempts yet
Problem
The owner of a cornfield, Minseok, wants to harvest the corn he grew carefully over the year. The field is a grid with rows and columns, and each cell has one corn plant. Minseok measured the value of each plant and assigned distinct integers .

Minseok starts outside the field. While moving outside the field, he can harvest the corn in any cell adjacent to the outside. Or, inside the field, he can move only through cells where he has already harvested corn, and harvest the corn in the cells directly above, below, left, or right of his current cell.
To control corn production, Minseok harvests only plants. He repeats times the process of harvesting the most valuable corn among the plants he can currently harvest. Find the positions of the plants he harvests, in order.
Input
The first line contains integers and (), separated by a space.
From the second line onward, the next lines each contain integers separated by spaces. The -th integer on the -th line, (), is the value of the corn in row , column of the grid.
The last line contains an integer ().
Output
Print lines. Each line contains the position (, ) of the corn Minseok harvests, in order. Here is the row and is the column of the grid.