← Home

64. Minimum Path Sum

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
graph traversalC++Markdown
64

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 64. Minimum Path Sum, the solution in this repository is mainly a graph traversal solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: graph traversal, dynamic programming, two pointers, backtracking.

The notes already sitting in the source point us in the right direction:

  • Backtracking
  • TLE
  • 10 / 61 test cases passed.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are backtrack, minPathSum.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Backtracking
02//TLE
03//10 / 61 test cases passed.
04class Solution {
05public:
06    int m, n;
07    
08    vector<vector<int>> dirs = {
09        {1, 0},
10        {-1, 0},
11        {0, 1},
12        {0, -1}
13    };
14    
15    void backtrack(int& minSum, int curSum, int curI, int curJ, vector<vector<int>>& grid, vector<vector<bool>>& visited){
16        if(curI == m-1 && curJ == n-1){
17            minSum = min(minSum, curSum);
18        }else{
19            for(vector<int>& dir : dirs){
20                int nextI = curI + dir[0];
21                int nextJ = curJ + dir[1];
22                if(nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n && !visited[nextI][nextJ]){
23                    cout << nextI << " " << nextJ << " | ";
24                    visited[nextI][nextJ] = true;
25                    backtrack(minSum, curSum+grid[nextI][nextJ], nextI, nextJ, grid, visited);
26                    visited[nextI][nextJ] = false;
27                }
28            }
29        }
30    };
31    
32    int minPathSum(vector<vector<int>>& grid) {
33        this->m = grid.size();
34        if(this->m == 0) return 0;
35        this->n = grid[0].size();
36        
37        int minSum = INT_MAX;
38        int curI = 0, curJ = 0;
39        int curSum = grid[curI][curJ];
40        vector<vector<bool>> visited(m, vector(n, false));
41        
42        backtrack(minSum, curSum, curI, curJ, grid, visited);
43        
44        return minSum;
45    }
46};
47
48//DP
49//Note: You can only move either down or right at any point in time.
50//Runtime: 12 ms, faster than 23.69% of C++ online submissions for Minimum Path Sum.
51//Memory Usage: 8.5 MB, less than 100.00% of C++ online submissions for Minimum Path Sum.
52class Solution {
53public:
54    int m, n;
55    
56    vector<vector<int>> dirs = {
57        {-1, 0},
58        {0, -1}
59    };
60    
61    int minPathSum(vector<vector<int>>& grid) {
62        this->m = grid.size();
63        if(this->m == 0) return 0;
64        this->n = grid[0].size();
65        
66        vector<vector<int>> dp = grid;
67        
68        for(int i = 0; i < m; i++){
69            for(int j = 0; j < n; j++){
70                int prevMin = INT_MAX;
71                for(vector<int>& dir : dirs){
72                    int prevI = i + dir[0];
73                    int prevJ = j + dir[1];
74                    if(prevI >= 0 && prevJ >= 0){
75                        prevMin = min(prevMin, dp[prevI][prevJ]);
76                    }
77                }
78                dp[i][j] += (prevMin == INT_MAX) ? 0 : prevMin;
79            }
80        }
81        
82        return dp[m-1][n-1];
83    }
84};
85
86//DP without extra space!
87//https://leetcode.com/problems/minimum-path-sum/discuss/23457/C%2B%2B-DP
88//Runtime: 8 ms, faster than 84.87% of C++ online submissions for Minimum Path Sum.
89//Memory Usage: 8.1 MB, less than 100.00% of C++ online submissions for Minimum Path Sum.
90class Solution {
91public:
92    int minPathSum(vector<vector<int>>& grid) {
93        int m = grid.size();
94        if(m == 0) return 0;
95        int n = grid[0].size();
96        
97        for(int i = 0; i < m; i++){
98            for(int j = 0; j < n; j++){
99                //INT_MAX means invalid
100                int top = (i-1>=0) ? grid[i-1][j] : INT_MAX;
101                int left = (j-1>=0) ? grid[i][j-1] : INT_MAX;
102                grid[i][j] += (min(top, left) == INT_MAX)?0:min(top, left);
103                // cout << grid[i][j] << " ";
104            }
105            // cout << endl;
106        }
107        
108        return grid[m-1][n-1];
109    }
110};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.