Skip to content

Instantly share code, notes, and snippets.

@jporcelli
Created October 20, 2014 22:16
Show Gist options
  • Save jporcelli/afc27e876df538254f97 to your computer and use it in GitHub Desktop.
Save jporcelli/afc27e876df538254f97 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.
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
for(int i = 1; i < m; i++){
grid[i][0] = grid[i-1][0] + grid[i][0];
}
for(int i = 1; i < n; i++){
grid[0][i] = grid[0][i-1] + grid[0][i];
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
grid[i][j] = Math.min(grid[i-1][j], grid[i][j-1]) + grid[i][j];
}
}
return grid[m-1][n-1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment