#P1653. Ski Resort Connectivity
Ski Resort Connectivity
Ski Resort Connectivity
Ron, John's cousin, has built a ski resort in Colorado for his cows. The ski resort is arranged as a grid with W columns and L rows, where each cell has a specific height \(H\) satisfying \(0 \le H \le 9999\). The cows can ski from one cell to a directly adjacent cell (up, down, left, or right) if and only if they are not skiing upward (i.e. they can move from a cell to an adjacent cell provided that the starting cell's height is not less than the adjacent cell's height).
Unfortunately, the cows are quite shy and do not dare to ski at vacation resorts organized by tourists. To ensure that any cell is accessible from any other cell, Ron plans to build some powerful bidirectional cable cars that can directly connect any two cells (and multiple cable cars can be built starting from the same cell). Since the cable cars are extremely expensive, Ron wants to build as few as possible. Your task is to compute the minimum number of cable cars needed.
Observation: The ski slopes do not guarantee bidirectional connectivity between cells. In fact, a cow can only move freely between cells if the two cells share the same height (since then movement is allowed both ways). Thus, the grid divides into several connected components, where two cells belong to the same component if and only if they are connected through adjacent cells having the same height. To ensure full connectivity across the entire resort, cable cars must be added to connect these components. The minimum number of cable car edges required is exactly the number of components minus one (by connecting the components in a spanning tree fashion).
Input Constraints:
- \(1 \le W, L \le 500\)
- \(0 \le H \le 9999\)
inputFormat
The first line contains two integers, W and L, representing the number of columns and rows respectively.
Each of the next L lines contains W integers, each representing the height \(H\) of a cell in that row.
outputFormat
Output a single integer: the minimum number of cable cars required to connect the entire ski resort.
sample
1 1
5
0
</p>