C#解leetcode 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.

 

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

代码如下:

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

 

posted on 2016-03-25 10:25  狂奔的蜗牛163  阅读(264)  评论(0编辑  收藏  举报