<AI/>
enru
All posts

Minimum path sum

LeetCode 64: Find the cheapest path from the top-left to the bottom-right cell of a grid, from brute force to in-place dynamic programming.

Difficulty
Medium
Published
Topics
#matrix#dynamic programming
Open on LeetCode

Problem Description

1 3 1 1 5 1 4 2 1 1 + 3 + 1 + 1 + 1 = 7

Write a function that returns the cost of the cheapest path from the top-left cell of a matrix to the bottom-right one. The value of a cell is the cost of moving into it. From each cell you can move either right or down.

Input: number[][] (an m by n matrix to search for the path in)

Output: number (the cost of the cheapest path)

Constraints

  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200

Examples

Input

[
    [1, 3, 1],
    [1, 5, 1],
    [4, 2, 1],
]

Answer: 7

Brute force approach

This is one of those problems where the brute force solution is actually harder to come up with than the optimal one. Still, let's go through it, since this kind of solution may be the first to come to mind in an interview. For brute force, we need to compare all possible paths. The easiest way to do that is to turn the matrix into a graph. Let's introduce a helper structure for the graph nodes.

typescript
type GraphNode = {
  price: number;
  children: GraphNode[];
};

By the problem statement, a graph node (a matrix cell) can be reached either from the cell to its left or from the cell above it. So to build the graph correctly, we keep a helper matrix (but now with graph nodes as values instead of numbers).

typescript
const nodeGrid: GraphNode[][] = [];
 
for (let i = 0; i < grid.length; i++) {
  nodeGrid.push([]);
 
  for (let j = 0; j < grid[i].length; j++) {
    const node: GraphNode = { price: grid[i][j], children: [] };
    nodeGrid[i].push(node);
 
    if (i > 0) {
      nodeGrid[i - 1][j].children.push(node);
    }
 
    if (j > 0) {
      nodeGrid[i][j - 1].children.push(node);
    }
  }
}

Now that we have a graph with all the links in place, we can use depth-first search to go through all possible paths from nodeGrid[0][0] to nodeGrid[m - 1][n - 1] and compare their costs.

typescript
const minPathSumTraverse = (root: GraphNode): number => {
  if (root.children.length === 0) {
    return root.price;
  }
 
  let minPathPrice = Infinity;
 
  for (const child of root.children) {
    minPathPrice = Math.min(minPathPrice, minPathSumTraverse(child));
  }
 
  return root.price + minPathPrice;
};

Complexity Analysis

Time Complexity

To find the minimum path, we need to go through all possible paths in the matrix. Each path consists of m + n - 1 cells. Except for the cells of the last row and the last column, there are 2 ways to go from every cell. The total number of possible paths, and therefore the complexity of the algorithm, can be estimated as O(2(n+m)).

Space Complexity

We created an additional graph of size m * n, so the additional memory is O(m * n).

Optimal approach

The optimal solution comes from dynamic programming: we split the problem into smaller subproblems.

Suppose we know the cheapest paths from grid[0][0] to grid[m - 2][n - 1] (the neighbour above the bottom-right cell) and to grid[m - 1][n - 2] (the neighbour to the left of the bottom-right cell).

Since we can only move right or down, the cheapest path to the bottom-right cell is:

grid[m-1][n-1] = min(grid[m-2][n-1], grid[m-1][n-2]) + grid[m-1][n-1]

In exactly the same way we can compute the cheapest paths to grid[m - 2][n - 1] and grid[m - 1][n - 2]. So we can compute the path cost to any cell if we know the costs to its left and upper neighbours.

Let's modify the input matrix in place (there's no immutability requirement, so we save memory), replacing the value of each cell with the cost of the cheapest path to it.

For that, a standard traversal of the matrix with nested loops over i and j is enough. We leave the first cell unchanged, since it's our starting point.

The path cost to any cell in the first row is the path cost to the previous cell plus the value of the current one (since any cell in the first row can only be reached from the left).

typescript
if (i === 0) {
  grid[i][j] = grid[i][j - 1] + grid[i][j];
  continue;
}

A similar check is needed for the cells in the first column (they can only be reached from above).

typescript
if (j === 0) {
  grid[i][j] = grid[i - 1][j] + grid[i][j];
  continue;
}

For all other cells we compute the cost by picking the cheaper of the two paths (from above or from the left).

typescript
grid[i][j] = Math.min(grid[i][j - 1], grid[i - 1][j]) + grid[i][j];

So after going over the whole matrix, the bottom-right cell holds the cost of the cheapest path to it. The final implementation:

typescript
export const minPathSum = (grid: number[][]): number => {
  let i = 0;
  let j = 0;
 
  for (i; i < grid.length; i++) {
    for (j = 0; j < grid[i].length; j++) {
      if (i == 0 && j == 0) {
        continue;
      }
 
      if (i == 0) {
        grid[i][j] = grid[i][j - 1] + grid[i][j];
        continue;
      }
 
      if (j == 0) {
        grid[i][j] = grid[i - 1][j] + grid[i][j];
        continue;
      }
 
      let minPrices = grid[i][j - 1];
      if (grid[i - 1][j] < minPrices) {
        minPrices = grid[i - 1][j];
      }
 
      grid[i][j] = minPrices + grid[i][j];
    }
  }
 
  return grid[i - 1][j - 1];
};

Complexity Analysis

Time Complexity

To compute the cheapest path, we go over the whole matrix once. So the overall complexity is O(m * n).

Space Complexity

O(1): the additional memory is constant.