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) {
if(grid.size() == 0 || grid[0].size() == 0)
return 0;
int x = grid.size();
int y = grid[0].size();
int sum[x][y];
int temp = 0;
for(int i = 0; i < x; i++)
{
temp += grid[i][0];
sum[i][0] = temp;
}
temp = 0;
for(int i = 0; i < y; i++)
{
temp += grid[0][i];
sum[0][i] = temp;
}
for(int i = 1; i < x; i++)
for(int j = 1; j < y; j++)
{
sum[i][j] = std::min(sum[i-1][j], sum[i][j-1]) + grid[i][j];
}
return sum[x-1][y-1];
}
};
Round 2:
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
if(grid.size() == 0)
return 0;
int min = INT_MAX, sum = 0;
dfs(grid, sum, 0, 0, min);
return min;
}
private:
void dfs(vector<vector<int> > &grid, int &sum, int x, int y, int &min)
{
sum += grid[x][y];
if(sum > min)
return;
if(x == grid.size()-1 && y == grid[0].size()-1)
{
min = std::min(sum, min);
return;
}
if(x < grid.size()-1)
{
dfs(grid, sum, x+1, y, min);
sum -= grid[x+1][y];
}
if(y < grid[0].size()-1)
{
dfs(grid, sum, x, y+1, min);
sum -= grid[x][y+1];
}
}
};