Train Line Construction
InterviewTime limit1sMemory limit64 MB
On an N by N grid with resident counts and blocked cells, find a 4-direction path between two stations minimizing the sum of cell weights along it.
- Level
Medium5 of 10
- Topics
- Graph, Shortest path, Heap, Dynamic programming
- Solved
- No attempts yet
Problem
MRT Corp is building railways across the country and has hired you.
The map is a square grid with cells on each side. Each cell holds the number of residents who live there. Everyone living on a cell the railway passes through has to move, so you pick the line between station and station that forces the fewest residents to move, and report that number. Some cells cannot carry track at all because the ground is unstable or a hill is in the way.
Track cannot run diagonally. It only connects cells up, down, left, and right. The line starts on the cell holding station and ends on the cell holding station , and both station cells are part of the line. The number of residents who move is the sum of over every cell the line passes through.
Input
The first line contains , the side length of the map. ()
The second line contains four integers , , , : the and coordinates of station , then the and coordinates of station . The coordinate is counted from the left and the coordinate from the top. The two stations sit on different cells. ()
Each of the next lines contains integers separated by spaces. The th number on the th of these lines is the value of the cell with coordinate and coordinate . A cell that cannot carry track is given as . ()
Output
Print the smallest number of residents who have to move, on one line.
If the two stations cannot be connected without laying track on a forbidden cell, print . If either station sits on a forbidden cell, no line can be built, so print in that case too.