C#解leetcode 64. Minimum Path Sum

时间:2023-12-05 22:04:56

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.

利用动态规划的知识求解。从左上开始,遍历到右下。考虑边界情况。

代码如下:

public class Solution {
public int MinPathSum(int[,] grid) { int row=grid.GetLength();
int col=grid.GetLength(); for(int i=;i<row;i++)
{
for(int j=;j<col;j++)
{
if(i==&&j!=)
{
grid[i,j]=grid[i,j]+grid[i,j-];
}
else if(i!=&&j==)
{
grid[i,j]=grid[i,j]+grid[i-,j];
}
else if(i==&&j==)
{
grid[i,j]=grid[i,j];
}
else
{
grid[i,j]= grid[i,j]+Math.Min(grid[i-,j],grid[i,j-]);
}
}
} return grid[row-,col-];
}
}