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;
}
相关推荐
视觉震撼3 小时前
为大型语言模型(LLM)自动化知识图谱流水线:2026年手册
人工智能·算法·机器学习
随意起个昵称3 小时前
【二分做题笔记】组装玩具
笔记·算法
Lips6113 小时前
2026.1.13力扣刷题笔记
笔记·算法·leetcode
小郭团队3 小时前
1_4_五段式SVPWM (传统算法反正切+DPWM0)算法理论与 MATLAB 实现详解
嵌入式硬件·算法·硬件架构·dsp开发
东方-教育技术博主3 小时前
处理VR头盔眼动数据的论文 领域有哪些分支,经典和前沿算法有啥
算法·vr
客卿1233 小时前
1/14-C语言重排数组
c语言·开发语言·算法
不穿格子的程序员3 小时前
从零开始刷算法——二叉树篇:验证二叉搜索树 + 二叉树中第k小的元素
java·开发语言·算法
老鼠只爱大米3 小时前
LeetCode算法题详解 76:最小覆盖子串
算法·leetcode·双指针·滑动窗口·最小覆盖子串·minwindow
HABuo3 小时前
【linux进程控制(一)】进程创建&退出-->fork&退出码详谈
linux·运维·服务器·c语言·c++·ubuntu·centos
CodeByV3 小时前
【算法题】链表
数据结构·算法