Minimum Path Sum in Rust

impl Solution {
    pub fn min_path_sum(grid: Vec<Vec<i32>>) -> i32 {
        let m = grid.len(); // Number of rows
        let n = grid[0].len(); // Number of columns
        let mut dp = vec![vec![0; n]; m]; // Dynamic programming table

        // Initialize the DP table with base case
        dp[0][0] = grid[0][0];

        // Fill the first row
        for j in 1..n {
            dp[0][j] = dp[0][j - 1] + grid[0][j];
        }

        // Fill the first column
        for i in 1..m {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }

        // Fill the rest of the DP table
        for i in 1..m {
            for j in 1..n {
                // The cell's value plus the minimum of the two adjacent cells (above and left)
                dp[i][j] = grid[i][j] + dp[i - 1][j].min(dp[i][j - 1]);
            }
        }

        // The last cell contains the minimum path sum
        dp[m - 1][n - 1]
    }
}

PrevNext