Ridges and Valleys
Time limit3sMemory limit128 MB
Count connected components of equal height in an n by n grid whose every boundary neighbor is strictly lower (ridge) or strictly higher (valley).
- Level
Medium7 of 10
- Topics
- Graph, DFS, BFS, Implementation
- Solved
- No attempts yet
Problem
Byteasar loves trekking in the hills. During his hikes he explores every ridge and valley nearby. To plan a trip and know how long it will take, he needs to know how many ridges and how many valleys lie in the area he is about to visit. Your job is to help him.
Byteasar gives you a map of his next expedition. The map is an square. For every field of the square (with ) its height is given.
Two fields are adjacent when they share a side or a corner. In other words, field is adjacent to , , , , , , and , whenever those fields still lie on the map.
A set of fields forms a ridge (respectively a valley) when:
- all fields in have the same height,
- is connected, that is, from any field in you can reach any other field in by stepping only between adjacent fields without ever leaving ,
- for every field and every field adjacent to , the heights satisfy (for a ridge) or (for a valley).
In particular, if every field on the map has the same height, all of them together form both a ridge and a valley.
Determine the number of ridges and the number of valleys in the landscape described by the map.
Input
The first line contains one integer (), the size of the map. Each of the next lines describes one row of the map: line (for ) contains integers (), separated by single spaces, the heights of the fields in row .
Output
Print a single line with two integers separated by one space: the number of ridges followed by the number of valleys in the landscape described by the map.
Hint


In the figures above the ridges are drawn with a solid line and the valleys with a dashed line.