Guarding the Farm

Interview

Time limit1sMemory limit128 MB

Summary
Count connected groups of equal-altitude cells, using 8-direction adjacency, that are surrounded only by lower altitude or the map edge.
Level

Medium4 of 10

Topics
Graph, DFS, BFS, Implementation
Solved
No attempts yet

Problem

Farmer John's farm has many hills, and he wants to place one guard on top of each hill to keep his valuable milk-cows safe. Help him find how many guards he needs — that is, how many hilltops appear on the map.

The map is given as an integer matrix with NN rows and MM columns (1<N≤7001 < N \le 700, 1<M≤7001 < M \le 700). Each entry is an altitude HijH_{ij} with 0≤Hij≤100000 \le H_{ij} \le 10000.

A hilltop is a group of one or more adjacent cells that all share the same value, such that the group is bounded exclusively by the edge of the map or by cells of lower (smaller) altitude. Two cells are adjacent if the absolute difference of their row coordinates is at most 11 and the absolute difference of their column coordinates is at most 11 (that is, the eight orthogonal and diagonal neighbors).

Input

  • Line 1: Two space-separated integers NN and MM.
  • Lines 2…N+12 \ldots N+1: Line i+1i+1 describes row ii of the matrix as MM space-separated integers HijH_{ij}.

Output

  • A single integer: the number of hilltops.

Hint

In the sample input there are three hilltops: the cell of altitude 44 in the top-left, one of the cells of altitude 22 in the lower part, and the cell of altitude 11 in the top-right corner.

Examples1

  1. Example 1

    Input
    8 7
    4 3 2 2 1 0 1
    3 3 3 2 1 0 1
    2 2 2 2 1 0 0
    2 1 1 1 1 0 0
    1 1 0 0 0 1 0
    0 0 0 1 1 1 0
    0 1 2 2 1 1 0
    0 1 1 1 2 1 0
    
    Expected output
    3