I have a binary matrix. Each column corresponds to a vertex in a graph. If I walk along the path (starting on the "col 1" vertex, then moving on to "col 2" etc.), I have to pay some fines. But since there are only so many police officers on the path, I can wait for some time until there is no police officer remaining on the next vertex, then go over. To clarify, the following matrix (first row is the "title" row):
A B C D
0 0 1 0
1 0 0 1
1 1 0 0
1 1 1 1
0 0 0 0
Encodes that I will pay if I am on A after waiting an extra 1, 2 or 3 hours before that point; on B, I will pay after 2 or 3 extra hours; on C, I will pay after 0 or 3 hours; on D, I will pay if I wait 1 or 3 hours.
As such, the optimal path here is "move to B, wait 1 hour, move to C, wait 1 hour, move to D", with total cost 0. (this path is marked with "X" on the following)
A B C D
X X 1 0
1 X X 1
1 1 X X
1 1 1 1
0 0 0 0
However, achieving 0 is not always possible, and I am only interested in one of the paths of minimal sum that goes from the top left entry to the right column.
How can I generate such a path efficiently?
The naive algorithm "generate all paths, find the minimum" works in exponential time, which doesn't feel optimal to me.
I thought of using a DP approach, but I was unable to formulate one that did not break on some cases, whether I try to add line-by-line or column-by-column