Minimum path sum in a 2D array

Find the minimum path sum in a 2D array from the top-left corner to the bottom-right corner.

Problem

Given a 2D array of integers, find a path from the top-left corner to the bottom-right corner that minimizes the sum of the integers along the path.
Input:
[[1, 3, 5],
 [2, 1, 4],
 [3, 2, 1]]
Output:
8 (1 + 3 + 2 + 1)

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int minPathSum(vector<vector<int>>& grid) {
    int m = grid.size();
    int n = grid[0].size();
    vector<vector<int>> dp(m, vector<int>(n, 0));
    dp[0][0] = grid[0][0];
    for (int i = 1; i < m; i++) {
        dp[i][0] = dp[i - 1][0] + grid[i][0];
    }
    for (int j = 1; j < n; j++) {
        dp[0][j] = dp[0][j - 1] + grid[0][j];
    }
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid [i][j];
        }
    }
    return dp[m - 1][n - 1];
}

int main() {
    vector<vector<int>> grid = {{1, 3, 5}, {2, 1, 4}, {3, 2, 1}};
    cout << minPathSum(grid) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution correctly solves the problem and uses a dynamic programming approach. The code is well-written and easy to follow.

Evaluated at: 2022-12-04 02:15:40