美文网首页
12_5矩阵最小路径和

12_5矩阵最小路径和

作者: X_Y | 来源:发表于2017-10-24 16:56 被阅读32次

    有一个矩阵map,它每个格子有一个权值。从左上角的格子开始每次只能向右或者向下走,最后到达右下角的位置,路径上所有的数字累加起来就是路径和,返回所有的路径中最小的路径和。

    给定一个矩阵map及它的行数n和列数m,请返回最小路径和。保证行列数均小于等于100.

    测试样例:
    [[1,2,3],[1,1,1]],2,3
    返回:4

    class MinimumPath {
    public:
        int getMin(vector<vector<int> > map, int n, int m) {
            // write code here
            vector< vector<int> > route(n, vector<int>(m, 0));
            route[0][0] = map[0][0];
            for(int i=1; i<m; ++i){
                route[0][i] = route[0][i-1] + map[0][i];
            }
            for(int i=1; i<n; ++i){
                route[i][0] = route[i-1][0] + map[i][0];
            }
            for(int i=1; i<n; ++i){
                for(int j=1; j<m; ++j){
                    int min_path = route[i-1][j] < route[i][j-1] ? route[i-1][j] : route[i][j-1];
                    route[i][j] = map[i][j] + min_path;
                }
            }
            return route[n-1][m-1];
        }
    };
    
    

    相关文章

      网友评论

          本文标题:12_5矩阵最小路径和

          本文链接:https://www.haomeiwen.com/subject/skrxpxtx.html