Under construction

Still being built. Things may change

Water Spreading

Time limit2.5sMemory limit1024 MB

Summary
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.
Level

Medium7 of 10

Topics
BFS, Graph, Matrix
Solved
No attempts yet

Problem

You are a graduate student studying how water flows over an N×NN \times N grid of land. Your goal is to find how many of the N2N^2 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 (X+1)(X+1) integers 0,1,2,⋯ ,X0, 1, 2, \cdots, X. State 00 means no water, and states 1,⋯ ,X1, \cdots, X mean water is present.
  • The cell where water is first poured has state XX.
  • When water spreads from a cell (x,y)(x,y) to an adjacent cell, the state of (x,y)(x,y) is unchanged.
  • For an integer ll greater than 11, water in a cell with state ll 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 (l−1)(l-1). Water does not spread to a cell whose state is (l−1)(l-1) or higher.
    • Every second, water spreads to each adjacent cell lower than the current cell. The spread water has state XX.
  • 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 (x,y)(x,y) has state 00 and no cell spreads water into (x,y)(x,y), its state stays 00.

Two cells (a,b)(a,b) and (x,y)(x,y) are adjacent when ∣a−x∣+∣b−y∣=1|a-x|+|b-y| = 1. (i,j)(i,j) denotes row ii, column jj. Given the height of each cell in the N×NN \times N grid and the cell where water is first poured, find the number of cells with water, that is, cells with state 1,⋯ ,X1, \cdots, X, after enough time has passed that water no longer spreads.

Input

The first line contains four integers NN, XX, xx, and yy, separated by spaces. (1≤N≤2 0001 \le N \le 2\,000, 1≤X≤2N1 \le X \le 2N, 1≤x,y≤N1 \le x, y \le N)

NN is the side length of the grid, XX is the state of the water poured first, and (x,y)(x,y) is the cell where water is first poured.

The next NN lines describe the grid. The jj-th integer hijh_{ij} on the ii-th line is the height of cell (i,j)(i,j). (0≤hij≤100 0000 \le h_{ij} \le 100\,000)

Output

Print the number of cells with water, meaning cells with state 1,⋯ ,X1, \cdots, X, after enough time has passed that water no longer spreads, on the first line.

Examples1

  1. Example 1

    Input
    8 3 6 3
    6 6 9 9 9 9 9 3
    6 6 6 9 9 9 3 3
    6 6 6 9 9 9 3 3
    7 7 7 9 9 2 3 3
    7 7 7 7 7 2 3 3
    8 8 8 8 7 4 3 3
    6 0 0 4 4 4 3 3
    6 6 6 6 4 4 4 3
    
    Expected output
    38