Created
February 16, 2013 11:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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