Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 16, 2013 11:28
Show Gist options
  • Select an option

  • Save pdu/4966485 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4966485 to your computer and use it in GitHub Desktop.
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. http://leetcode.com/onlinejudge#question_64
#define MAXN 1000
#define MAX_INT 0x7fffffff
int ans[MAXN][MAXN];
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
int n = grid.size();
int m = grid[0].size();
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) {
ans[i][j] = MAX_INT;
if (i == 0 && j == 0)
ans[i][j] = grid[i][j];
if (i != 0)
ans[i][j] = min(ans[i][j], ans[i - 1][j] + grid[i][j]);
if (j != 0)
ans[i][j] = min(ans[i][j], ans[i][j - 1] + grid[i][j]);
}
return ans[n - 1][m - 1];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment