Monday Blues
InterviewTime limit1sMemory limit512 MB
Given an N by M grid with costly buildable cells and blocked or unbuildable cells, find the minimum total cost to cut every path from (1,1) to (N,M), or report that no placement can do it.
- Level
Hard8 of 10
- Topics
- Graph, Minimum spanning tree, Shortest path, Implementation
- Solved
- No attempts yet
Problem
It is Sunday night, and the thought of going to school tomorrow is starting to hurt.
To have an excuse for skipping school, you decide to build walls on the way from home to school so that every route is blocked.
The neighborhood is a grid of cells. Home is at and school is at .
Each cell is one of three kinds:
- A cell that already has a wall (written as ).
- A cell with no wall where a wall cannot be built (written as ).
- A cell with no wall where a wall can be built for a price (written as that price).
You will build walls on cells of the third kind so that no route from home to school remains. To save money, you want the total cost to be as small as possible. In some cases the routes cannot be blocked no matter where you build, and you must detect that as well.
When moving from home to school, you can only step up, down, left, or right (not diagonally), and you cannot leave the grid. You cannot enter a cell that has a wall. The cells of home and school are guaranteed to be cells where a wall cannot be built.
Input
The first line contains the number of rows and the number of columns , separated by a space ().
Each of the next lines contains integers. The -th integer on the -th of these lines describes cell . means the cell already has a wall, and means a wall cannot be built there. An integer of or more means a wall can be built there, and the value is the cost of building it. Every cost is an integer not exceeding .
The cells of home and school, and , are always given as .
Output
Print the minimum cost to make school unreachable from home. If the routes cannot be blocked at all, print .
Hint
In the first example, the walls can be placed as follows. # is the existing wall, * is a newly built wall, and . is a cell without a wall.
..#
.*.
.*.
Each of the two new walls costs , so the total cost is .