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.
Java Solution 1: Depth-First Search
A native solution would be depth-first search. It’s time is too expensive and fails the online judgement.
public int minPathSum(int[][] grid) { return dfs(0,0,grid); } public int dfs(int i, int j, int[][] grid){ if(i==grid.length-1 && j==grid[0].length-1){ return grid[i][j]; } if(i<grid.length-1 && j<grid[0].length-1){ int r1 = grid[i][j] + dfs(i+1, j, grid); int r2 = grid[i][j] + dfs(i, j+1, grid); return Math.min(r1,r2); } if(i<grid.length-1){ return grid[i][j] + dfs(i+1, j, grid); } if(j<grid[0].length-1){ return grid[i][j] + dfs(i, j+1, grid); } return 0; } |
Java Solution 2: Dynamic Programming
public int minPathSum(int[][] grid) { if(grid == null || grid.length==0) return 0; int m = grid.length; int n = grid[0].length; int[][] dp = new int[m][n]; dp[0][0] = grid[0][0]; // initialize top row for(int i=1; i<n; i++){ dp[0][i] = dp[0][i-1] + grid[0][i]; } // initialize left column for(int j=1; j<m; j++){ dp[j][0] = dp[j-1][0] + grid[j][0]; } // fill up the dp table for(int i=1; i<m; i++){ for(int j=1; j<n; j++){ if(dp[i-1][j] > dp[i][j-1]){ dp[i][j] = dp[i][j-1] + grid[i][j]; }else{ dp[i][j] = dp[i-1][j] + grid[i][j]; } } } return dp[m-1][n-1]; } |
should be said : you can only take step down to next row, or next column
obv , dp array no need so big.
how i call it in the main????
could you point out what could be next step?
you really took /Brevity is the sister of talent. – Anton Chekhov Quote/ to extreme!
In the inner loop it can be dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
It starts to irritate that the problems are not precise.
You can only move either down or right at any point in time. – Leet Code
Exactly
static int minPath(int[][] a) {
if (a == null || a.length == 0) {
return 0;
}
int m = a.length;
int n = a[0].length;
for (int i = 1; i < m; i++) {
a[i][0] = a[i – 1][0] + a[i][0];
}
for (int j = 1; j < n; j++) {
a[0][j] = a[0][j – 1] + a[0][j];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
a[i][j] = Math.min(a[i – 1][j], a[i][j – 1]) + a[i][j];
}
}
return a[m – 1][n – 1];
}
For 2nd solution we can use only one row for temp datas – O(n) extra space:
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0)
return 0;
int[] temp = new int[grid[0].length];
for (int i = 0; i < grid.length; i++)
for (int j = 0; j 0)
if (i > 0)
temp[j] = Math.min(temp[j], temp[j - 1]);
else
temp[j] = temp[j - 1];
temp[j] += grid[i][j];
}
return temp[temp.length - 1];
}
Dijkstra algorithm is the solution.
The recursive dfs method can be made more efficient with memoization. Store each i,j value previously computed and call it each it you need it – following the first computation
The DP assumes that we can only walk down, but not up. If we can walk up, this is a a shortest ptah problem