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;
}
相关推荐
晓纪同学9 分钟前
EffctiveC++_第三章_资源管理
开发语言·c++·算法
蚊子码农16 分钟前
每日一题--C语言指针与内存泄漏:一道小问题的深度复盘
c语言·开发语言
Fanfanaas16 分钟前
Linux 系统编程 进程篇(一)
linux·运维·服务器·c语言·开发语言·网络·学习
水云桐程序员26 分钟前
C语言编程基础,输入与输出
c语言·开发语言·算法
ZPC821029 分钟前
MoveIt Servo 与自己编写的 Action Server 通信
人工智能·算法·机器人
jllllyuz31 分钟前
采用核函数的极限学习机(KELM)MATLAB实现
算法
jolimark33 分钟前
微软不支持C开发Win32原因剖析,及C语言在系统开发中的优势
c语言·微软·mfc·系统开发·win32
apcipot_rain39 分钟前
【天梯赛】2026天梯赛模拟赛——题解
开发语言·c++·算法·蓝桥杯·天梯赛
.柒宇.1 小时前
力扣hot100之最大子数组和(Java版)
数据结构·算法·leetcode
黎阳之光1 小时前
非视距·自愈·广覆盖|黎阳之光1.4&5.8GHz宽带自愈网无线基站,重构工业级无线通信
大数据·人工智能·算法·安全·数字孪生