Competitive Contagion
InterviewTime limit1sMemory limit256 MB
Simulate a grid where each cell's virus spreads to four neighbors every second, with lower-numbered viruses spreading first and blocking others, then report the virus at one cell after S seconds.
- Level
Medium5 of 10
- Topics
- BFS, Simulation, Graph, Sorting
- Solved
- No attempts yet
Problem
There is a test tube of size . The test tube is divided into cells, and a virus may exist in a particular cell. Every virus belongs to one of the virus types numbered 1 through .
Every virus in the test tube multiplies each second in the up, down, left, and right directions. Each second, viruses of lower-numbered types multiply before those of higher-numbered types. Also, during the multiplication process, if a virus already exists in a particular cell, no other virus can enter that cell.
Given the size of the test tube and the positions of the viruses, write a program that prints the type of the virus that exists at after seconds. If no virus exists at that position after seconds, print 0. Here and denote the row and column positions, respectively, and the top-left cell of the test tube is .
For example, suppose there is a test tube of size as follows. Distinct viruses 1, 2, and 3 are located at , , and , respectively. Let us compute the type of the virus that exists at after 2 seconds.

After 1 second, the state of the test tube is as follows.

After 2 seconds, the state of the test tube is as follows.

As a result, the type of the virus that exists at after 2 seconds is virus 3. Therefore, printing 3 is the correct answer.
Input
The first line gives the natural numbers and , separated by a space. (, ) From the second line, lines give the information of the test tube. Each row consists of elements, and the number of the virus existing at that position is given separated by spaces. If no virus exists at that position, 0 is given. Also, every virus number is given as a natural number no greater than . The -th line gives , , and , separated by spaces. (, )
Output
Print the type of the virus that exists at after seconds. If no virus exists at that position after seconds, print 0.