Sandbagging the Village
The river is rising, and the village elder has handed you a survey map of the valley. The map is a
grid of R rows and C columns, and every cell holds one character:
~— river. The flood starts from every river cell.H— a house.#— rock. Water never enters a rock cell..— open ground. Blocking it takes 1 sandbag.1…9— rough ground (ditches, hedges, rubble). Blocking a cell marked with digitdtakesdsandbags.
Water spreads from a cell to the cells directly above, below, left and right of it (never diagonally), as long as the target cell is not rock and has not been blocked. Water never leaves the map: cells outside the grid simply don't exist. Note that water flows freely through houses, too: a flooded house floods its neighbours.
You may block any set of open-ground and rough-ground cells; a blocked cell behaves like rock. River
cells and houses can't be blocked. Find the smallest total number of sandbags needed so that the
water cannot reach any house. If no choice of cells works, which happens exactly when some house
shares a side with a river cell, print -1.
If the map has no river cells or no houses, or the rocks already keep every house dry, no sandbags
are needed and the answer is 0.
Input
The first line contains two integers R and C (1 ≤ R, C ≤ 100).
Each of the next R lines contains a string of exactly C characters, each one of ~, H, #,
. or a digit from 1 to 9.
Output
Print one integer: the minimum total number of sandbags, or -1 if the houses can't be protected.
Notes
In the first example the cheapest wall is the row of three cells just above the house's row, costing
1 + 1 + 1 = 3. Walling in the house directly would need 1 + 5 + 5 = 11 sandbags.
In the second example, blocking the 9 cell next to the river would work but costs 9. Blocking the
two . cells at row 2, column 3 and row 3, column 2 (1-based) costs only 2. The house in the
bottom-left corner is already shut in by rock.
In the third example the house in the second row touches the river cell to its right, so the answer
is -1 even though the other house is safe.