[LeetCode] 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.

 

Hide Tags
 Array Dynamic Programming
 
     找矩阵左上到右下的最短路径,标准的动态规划。
  1. 初始化统计矩阵的最上行,最右列。
  2. 从上往下,从左到右填写每格。
  3. 输出结果
 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 
 5 
 6 class Solution {
 7 public:
 8     int minPathSum(vector<vector<int> > &grid) {
 9         int nrow = grid.size();
10         if(nrow==0) return 0;
11         int ncol = grid[0].size();
12         vector<vector<int> > cnt(nrow,vector<int>(ncol,0));
13         cnt[0][0] = grid[0][0];
14         for(int i =1;i<nrow;i++)
15             cnt[i][0]=cnt[i-1][0]+grid[i][0];
16         for(int j = 1;j<ncol;j++)
17             cnt[0][j]=cnt[0][j-1] + grid[0][j];
18         for(int i=1;i<nrow;i++){
19             for(int j=1;j<ncol;j++){
20                 cnt[i][j] = grid[i][j] + min(cnt[i-1][j],cnt[i][j-1]);
21             }
22         }
23         return cnt[nrow-1][ncol-1];
24     }
25 };
26 
27 int main()
28 {
29     vector<vector<int> > grid({{1,2,3},{4,5,6},{7,8,9}});
30     Solution sol;
31     cout<<sol.minPathSum(grid)<<endl;
32     for(int i=0;i<grid.size();i++){
33         for(int j=0;j<grid[i].size();j++)
34             cout<<grid[i][j]<<" ";
35         cout<<endl;
36     }
37     return 0;
38 }
View Code

 

posted @ 2014-12-09 18:41  A_zhu  阅读(167)  评论(0编辑  收藏  举报