# 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.

class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
int row = grid.size(),col;
if(row == 0)return 0;
else col = grid[0].size();
vector<vector<int> >dp(row+1, vector<int>(col+1, INT_MAX));
dp[0][1] = 0;
for(int i = 1; i <= row; i++)
for(int j = 1; j <= col; j++)
dp[i][j] = grid[i-1][j-1] + min(dp[i][j-1], dp[i-1][j]);
return dp[row][col];
}
};

）））                          本文地址

class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
int row = grid.size(),col;
if(row == 0)return 0;
else col = grid[0].size();
vector<int >dp(col+1, INT_MAX);
dp[1] = 0;
for(int i = 1; i <= row; i++)
for(int j = 1; j <= col; j++)
dp[j] = grid[i-1][j-1] + min(dp[j], dp[j-1]);
return dp[col];
}
};

dp[k][i][j] = max(dp[k-1][i-1][j-1], dp[k-1][i][j], dp[k-1][i-1][j], dp[k-1][i][j-1]) + grid[k-i][i-1] + grid[k-j][j-1]  （我们假设在起始位置时就已经走了一步）

int max2PathSum(vector<vector<int> > grid)
{
int row = grid.size(), col = grid[0].size();
vector<vector<vector<int> > > dp(row+col, vector<vector<int> >(col+1, vector<int>(col+1, 0)));
for(int step = 2; step <= row+col-2; step++)
for(int i = max(1, step-row+1); i <= step && i <= col; i++)
for(int j = i+1; j <= step && j <= col; j++)
{

dp[step][i][j] = max(max(dp[step-1][i][j], dp[step-1][i-1][j-1]), max(dp[step-1][i-1][j], dp[step-1][i][j-1]));
dp[step][i][j] += (grid[step-i][i-1] + grid[step-j][j-1]);
}
return dp[row+col-2][col-1][col] + 2*grid[row-1][col-1] + 2*grid[0][0];
}

nyoj中 传纸条（一）就是这个问题，可以在这一题中测试上述函数的正确性，测试代码如下：

int main()
{
int n;
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
int row, col;
scanf("%d%d", &row, &col);
vector<vector<int> >grid(row, vector<int>(col));
for(int a = 0; a < row; a++)
for(int b = 0; b < col; b++)
scanf("%d", &grid[a][b]);
printf("%d\n", max2PathSum(grid));
}
return 0;
}

【版权声明】转载请注明出处http://www.cnblogs.com/TenosDoIt/p/3774804.html

posted @ 2014-06-07 15:00  tenos  阅读(3328)  评论(0编辑  收藏  举报