Given a
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.
Thoughts:
Because the grid is filled with non-negative numbers. Standing at any position (), the minimum sum we can get is
(minimum sum starting from
, minimum sum starting from
). Hence we find the recursive structure of this problem. The base case would be one element only, one row only and one column only. Notice that we could end up with repeating computations a lot (e.g., right->down and down->right), hence we should employ dynamic programming, in which we introduce a hashmap to cache the partial result.
Code (Java):
public class Solution {
private Map<List<Integer>, Integer> map =
new HashMap<List<Integer>, Integer>();
public int minPathSum(int[][] grid) {
map.clear();
return minPathSumRec(grid, 0, 0);
}
private int minPathSumRec(int[][] grid, int i, int j) {
List<Integer> pair = new ArrayList<Integer>();
pair.add(i);
pair.add(j);
if(map.get(pair) != null)
return map.get(pair);
else {
int r = grid[i][j];;
if(i == grid.length-1 && j == grid[0].length - 1)
r += 0;
else if(i == grid.length - 1)
r += minPathSumRec(grid, i, j + 1);
else if(j == grid[0].length - 1)
r += minPathSumRec(grid, i + 1, j);
else
r += Math.min(minPathSumRec(grid, i + 1, j),
minPathSumRec(grid, i, j + 1));
map.put(pair, r);
return r;
}
}
}
Code (C++):
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
cache.clear();
return minPathSumRec(grid, 0, 0);
}
private:
map<vector<int>, int> cache;
int minPathSumRec(vector<vector<int> > &grid, int i, int j) {
vector<int> pair(2);
pair[0] = i;
pair[1] = j;
if(cache.find(pair) != cache.end())
return cache[pair];
else {
int r = grid[i][j];
if(i == grid.size() -1 && j == grid[0].size() - 1)
r += 0;
else if(i == grid.size() - 1)
r += minPathSumRec(grid, i, j + 1);
else if(j == grid[0].size() - 1)
r += minPathSumRec(grid, i + 1, j);
else
r += min(minPathSumRec(grid, i, j + 1),
minPathSumRec(grid, i + 1, j));
cache[pair] = r;
return r;
}
}
};