Guarding the Farm
InterviewTime limit1sMemory limit128 MB
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 rows and columns (, ). Each entry is an altitude with .
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 and the absolute difference of their column coordinates is at most (that is, the eight orthogonal and diagonal neighbors).
Input
- Line 1: Two space-separated integers and .
- Lines : Line describes row of the matrix as space-separated integers .
Output
- A single integer: the number of hilltops.
Hint
In the sample input there are three hilltops: the cell of altitude in the top-left, one of the cells of altitude in the lower part, and the cell of altitude in the top-right corner.