LeetCode //C - 64. Minimum Path Sum

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.

Note: You can only move either down or right at any point in time.

Example 1:

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]
Output: 7
Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Example 2:

Input: grid = [[1,2,3],[4,5,6]]
Output: 12

Constraints:
  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 200
  • 0 <= grid[i][j] <= 200

From: LeetCode

Link: 64. Minimum Path Sum


Solution:

Ideas:

This function assumes that the memory for grid has already been allocated and that gridSize and gridColSize are correctly set to reflect the dimensions of grid. The min function is a helper to find the minimum of two numbers.

The function calculates the minimum path sum in a bottom-up manner, filling in the dp table from the top-left to the bottom-right. After calculating the minimum path sum, it cleans up the allocated memory for dp and returns the result.

Code:
c 复制代码
int minPathSum(int** grid, int gridSize, int* gridColSize) {
    // The gridSize is the number of rows, and gridColSize[0] is the number of columns.
    int i, j;
    
    // Allocate space for the dp matrix
    int **dp = (int **)malloc(gridSize * sizeof(int *));
    for(i = 0; i < gridSize; i++) {
        dp[i] = (int *)malloc(gridColSize[0] * sizeof(int));
    }
    
    // Initialize the top-left corner
    dp[0][0] = grid[0][0];
    
    // Fill the first row (only right moves are possible)
    for(j = 1; j < gridColSize[0]; j++) {
        dp[0][j] = dp[0][j - 1] + grid[0][j];
    }
    
    // Fill the first column (only down moves are possible)
    for(i = 1; i < gridSize; i++) {
        dp[i][0] = dp[i - 1][0] + grid[i][0];
    }
    
    // Fill the rest of the dp matrix
    for(i = 1; i < gridSize; i++) {
        for(j = 1; j < gridColSize[0]; j++) {
            dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]);
        }
    }
    
    // The bottom-right corner has the result
    int result = dp[gridSize - 1][gridColSize[0] - 1];
    
    // Free the dp matrix
    for(i = 0; i < gridSize; i++) {
        free(dp[i]);
    }
    free(dp);
    
    return result;
}

// Helper function to find the minimum of two numbers
int min(int a, int b) {
    return (a < b) ? a : b;
}
相关推荐
✿ ༺ ོIT技术༻4 分钟前
剑指offer第2版:链表系列
数据结构·算法·链表
mit6.8247 分钟前
[Nagios Core] struct监控对象 | 配置.cfg加载为内存模型
c语言·开发语言
yiridancan28 分钟前
终极剖析HashMap:数据结构、哈希冲突与解决方案全解
java·数据结构·算法·哈希算法
满分观察网友z30 分钟前
性能优化大作战:从 O(N*M) 到 O(N),我的哈希表奇遇记(1865. 找出和为指定值的下标对)
算法
点云SLAM2 小时前
二叉树算法详解和C++代码示例
数据结构·c++·算法·红黑树·二叉树算法
今天背单词了吗98010 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
jdlxx_dongfangxing10 小时前
进制转换算法详解及应用
算法
why技术11 小时前
也是出息了,业务代码里面也用上算法了。
java·后端·算法
2501_9228955812 小时前
字符函数和字符串函数(下)- 暴力匹配算法
算法
IT信息技术学习圈12 小时前
算法核心知识复习:排序算法对比 + 递归与递推深度解析(根据GESP四级题目总结)
算法·排序算法