Problem:
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.
Analysis:
Solutions:
C++:
int minPathSum(vector<vector<int>>& grid) {
if(grid.empty())
return 0;
int rows = grid.size();
for(int row = 1; row < rows; ++row) {
grid[row][0] += grid[row - 1][0];
}
int cols = grid[0].size();
for(int col = 1; col < cols; ++col) {
grid[0][col] += grid[0][col - 1];
}
for(int row = 1; row < rows; ++row) {
for(int col = 1; col < cols; ++col)
grid[row][col] += min(grid[row - 1][col], grid[row][col - 1]);
}
return grid[rows - 1][cols - 1];
}
Java:
Python: