Water Spreading
Time limit2.5sMemory limit1024 MB
Given an N by N grid of heights and a starting cell with state X, count the cells that get water as it spreads to equal-height and lower neighbors.
Problem
You are a graduate student studying how water flows over an grid of land. Your goal is to find how many of the cells, each with a given height, receive water. After years of research, you found that water spreads according to the following rules.
- Each cell holds a water state, which is one of the integers . State means no water, and states mean water is present.
- The cell where water is first poured has state .
- When water spreads from a cell to an adjacent cell, the state of is unchanged.
- For an integer greater than , water in a cell with state spreads by the following rules.
- Every second, water spreads to each adjacent cell with the same height as the current cell. The spread water has state . Water does not spread to a cell whose state is or higher.
- Every second, water spreads to each adjacent cell lower than the current cell. The spread water has state .
- Water can spread from one cell many times. Spreading happens at all cells at the same time.
- If several cells spread water into the same cell at once, its state is the maximum of the spread states.
- If a cell has state and no cell spreads water into , its state stays .
Two cells and are adjacent when . denotes row , column . Given the height of each cell in the grid and the cell where water is first poured, find the number of cells with water, that is, cells with state , after enough time has passed that water no longer spreads.
Input
The first line contains four integers , , , and , separated by spaces. (, , )
is the side length of the grid, is the state of the water poured first, and is the cell where water is first poured.
The next lines describe the grid. The -th integer on the -th line is the height of cell . ()
Output
Print the number of cells with water, meaning cells with state , after enough time has passed that water no longer spreads, on the first line.