1
votes

So the question is

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. You can only move down and to the right.

This is a common interview question on software engineering interviews, it is easily solved by implementing a dynamic programming table in order to discern what path is the least costly.

I am now wondering, is there an easy way to solve an alternative problem? Which would be to find the exact sum of a path in an mxn grid.

For instance the input would be a 3x3 matrix and the target sum would be lets say 4. What type of programming technique should be used in order to find a path that equals exactly 4 to the bottom right corner from the top left corner.

1
Interesting question. If you can't find answers here, you might try the computer science stackexchange. - Stef

1 Answers

0
votes

Breadth(or depth)-first search with pruning:

Since you can only move down and right and we you looking for an exact number, you need to look through all the possible paths. Fortunately, since the numbers are non-negative, we can prune the search quite a bit - as soon as the cost of the path prefix is greater than your target(e.g. 4), the resulting path will definitely have greater cost then your target so you can terminate this branch of computation.

Note: if you are unlucky you will still need to look through all (2N - 2)!/((N-1)! * (N-1)!) possible paths, where N is the side of the grid. (N-1 times down, N-1 times right, permutate with repetition since downs and rights are indistinguishable within their own category.) One such example would be a grid where all paths are of lower total than your target.

Proof: Suppose there is a path you didn't check. If I am your enemy and I am setting the grid while knowing you algorithm. I can always set up the unchecked path to be the one with the target sum.