Watersheds (Small)
InterviewTime limit5sMemory limit512 MB
Given a height grid, follow each cell's outflow to its sink and label cells by shared sink, choosing basin letters to make the row-wise string smallest.
- Level
Medium4 of 10
- Topics
- Graph, DFS, Union-find, Simulation
- Solved
- No attempts yet
Problem
Geologists divide an area of land into regions by where rainfall flows down to. Each region is a drainage basin.
You are given an elevation map, a two dimensional array of altitudes. Label the map so that cells in the same drainage basin carry the same label, under these rules.
- From each cell, water flows down to at most one of its 4 neighboring cells (north, west, east, south).
- If no neighbor of a cell has a lower altitude than the cell itself, water does not flow out of it. That cell is a sink.
- Otherwise water flows from the cell to the neighbor with the lowest altitude.
- When several neighbors tie for the lowest altitude, water picks the first of them in this order: north, west, east, south.
Every cell that drains directly or indirectly into the same sink belongs to the same drainage basin, and a sink belongs to its own basin. Label each basin with a distinct lower case letter so that concatenating the rows of the labeled map from top to bottom gives the lexicographically smallest string. The basin of the north western cell is therefore always labeled a.
Input
The first line contains the number of maps .
Each map begins with a line holding two integers and , the height and the width of the map in cells. The next lines describe the rows of the map from north to south. Each of those lines holds integers, given from west to east, which are the altitudes of the cells.
Limits
- altitude
- every map has at most 26 drainage basins
Output
For each map print lines. The first line is
Case #X:
where is the number of the map, counting from 1. The next lines hold the basin labels of the cells in the same order as the input, one line per map row, with a single space between the labels on a line.
Hint
In the first example the upper right corner and the lower left corner are sinks. Water on the diagonal flows toward the lower left because 5 is lower than 6.