Problem B
Cops and Robbers
The First Universal Bank of Denview has just been robbed! You want to catch the robbers before they leave the state.
The state of Calirado can be represented by a rectangular
To catch the robbers, you can set up barricades. Barricades are placed inside a grid cell, and prevent the robbers from traveling into the cell (from any direction). Each grid square consists of a different type of terrain, with different cost for placing a barricade. You cannot place a barricade on the bank (‘B’) or on any cell containing a dot (‘.’), though the robbers can travel freely through these cells. Every other cell will contain a lowercase English letter, indicating a terrain type.
Find the cheapest way to prevent the robbers from escaping Calirado.
Input
The first line contains three integers
Output
Print one integer, the minimum total cost of the barricades that you need to place to prevent the robbers from escaping. If there is no way to prevent the robbers from escaping, print -1 instead.
In the first example, the minimum cost is to barricade the
central three squares on each side of the bank for a total cost
of
In the second example, since the bank is on the border, there is no way to prevent the robbers from escaping the state.
In the third example, we must prevent the robbers from
leaving the bank to the top, bottom, and right, or else we
cannot prevent them from leaving the state. To the left,
however, it is cheaper to allow passage through the ‘b’ cell, and then barricade in each of the three
directions from there. The total cost is
Sample Input 1 | Sample Output 1 |
---|---|
5 5 1 aaaaa a...a a.B.a a...a aaaaa 1 |
12 |
Sample Input 2 | Sample Output 2 |
---|---|
2 2 1 aB aa 1 |
-1 |
Sample Input 3 | Sample Output 3 |
---|---|
4 3 3 .abc abBc .abc 1 7 5 |
22 |