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.
Hard8GraphMinimum spanning treeShortest pathImplementationInterviewNo attempts yetTime limit1sMemory limit512 MBIt 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 N×M cells. Home is at (1,1) and school is at (N,M).
Each cell is one of three kinds:
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.
The first line contains the number of rows N and the number of columns M, separated by a space (2≤N,M≤300).
Each of the next N lines contains M integers. The j-th integer on the i-th of these lines describes cell (i,j). −2 means the cell already has a wall, and −1 means a wall cannot be built there. An integer of 0 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 109.
The cells of home and school, (1,1) and (N,M), are always given as −1.
Print the minimum cost to make school unreachable from home. If the routes cannot be blocked at all, print −1.
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 1, so the total cost is 2.