Peaks

Time limit2sMemory limit256 MB

Summary
Count grid cells that stay locally maximal when reachability is restricted to cells within height d of the starting cell, for many test cases up to 500x500.
Level

Hard8 of 10

Topics
Union-find, Sorting, Graph
Solved
No attempts yet

Problem

Sang-geun works at a company that makes large maps. His current task is to find the peaks of mountains in a landscape.

You are given a grid map where each cell has a height. Consider a cell whose height is hh. Starting from this cell, you may move between orthogonally adjacent cells (up, down, left, right), but you are never allowed to step onto a cell whose height is h−dh-d or lower. If, under this restriction, it is impossible to reach any cell taller than hh, then the cell is called a dd-peak. In other words, a cell is a dd-peak if, using only cells with height greater than h−dh-d, you cannot walk to any cell higher than itself.

For example, a cell that is only slightly lower than a summit is not a peak if it connects directly to a higher summit without ever descending to low ground. Conversely, if reaching any higher cell forces you to pass through some sufficiently low cell (height h−dh-d or lower), then the cell is a dd-peak.

Given the height of every cell, write a program that counts how many cells are dd-peaks.

Input

The first line contains the number of test cases TT (1≤T≤1001 \le T \le 100).

The first line of each test case contains the map's number of rows nn, number of columns mm, and an integer dd (1≤n,m≤5001 \le n, m \le 500, 1≤d≤1091 \le d \le 10^9). Each of the next nn lines contains mm integers, the heights hh of the cells (0≤h≤1090 \le h \le 10^9).

Output

For each test case, print the number of dd-peaks on its own line.

Examples7

  1. Example 1

    Input
    1
    6 10 2
    0 0 0 0 0 0 0 0 0 0
    0 1 2 1 1 1 1 0 1 0
    0 2 1 2 1 3 1 0 0 0
    0 1 2 1 3 3 1 1 0 0
    0 2 1 2 1 1 1 0 2 0
    0 0 0 0 0 0 0 0 0 0
    
    Expected output
    4
    
  2. Example 2

    Input
    1
    3 3 3
    5 5 5
    5 5 5
    5 5 5
    
    Expected output
    9
    
  3. Example 3

    Input
    1
    1 1 1
    7
    
    Expected output
    1
    
  4. Example 4

    Input
    1
    1 5 1
    1 2 3 4 5
    
    Expected output
    1
    
  5. Example 5

    Input
    2
    2 2 1
    1 1
    1 1
    2 2 1000000000
    5 3
    4 9
    
    Expected output
    4
    1
    
  6. Example 6

    Input
    1
    3 3 1000000000
    1 2 3
    4 9 4
    3 2 1
    
    Expected output
    1
    
  7. Example 7

    Input
    2
    2 3 1000000000
    7 1 7
    1 1 1
    1 1 5
    5
    
    Expected output
    2
    1