64 Minimum Path Sum
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.
Example:
Note: You can only move either down or right at any point in time.
The Idea: This problem reminded me of seam carving in computer vision. This problem follows a familiar design, and the proof (via induction) as to why it works is the same. Suppose we have the following matrix
Begin by accumulating the top row and left column. We do this because it this sort of logic is unique to only these areas of the matrix. Performing this separately simplifies the logic later. What distinguishes these elements is that they can only accumulate from one direction respectively (towards the right, and down). Every other matrix element has one of two options.
Next, we work on the bottom right sub matrix (matrix[1:end][1:end]
). These areas have two options (to take a path from either the bottom or top. To understand why this works, we can see how this works for the base case (first row), and then inductively prove how every next row can independently be treated exactly the same as the base case.
It then follows that the bottom right matrix element is the minimum accumulative sum. If we'd like we can backtrack to actually find this path. Simply take the minimum left or top matrix element beginning from the bottom right matrix element until the starting matrix element is reached.
Complexity: O(n) time, and O(n) extra space
Last updated