Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added MinPathSum, MinPathFallingSum Algorithms, using Recursion + dp #219

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions Advance.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1092,4 +1092,92 @@ solution: -----python-----

print (out_)

17) Write a Algorithm For Finding Minimum Path Sum and Minium Path Falling Sum in a Grid ?

// JAVA Algorithm
// Recusion + Dynamic Programming

// Minimum Path Sum;

class Solution {
public int minPathSum(int[][] grid) {

int m = grid.length;
int n = grid[0].length;

int[][] dp = new int [m][n];

for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
dp[i][j] = -1;
}
}
return MinimumPathSum (0, 0, m, n, grid, dp);
}

static int MinimumPathSum (int i, int j, int m, int n, int[][] grid, int[][] dp) {

if (i == m - 1 && j == n - 1) {
return grid[i][j];
}

if (i == m || j == n) {
return Integer.MAX_VALUE;
}

if (dp[i][j] != -1) {
return dp[i][j];
}

int right = MinimumPathSum (i, j + 1, m, n, grid, dp);
int down = MinimumPathSum (i + 1, j, m, n, grid, dp);

dp[i][j] = grid[i][j] + Math.min (right, down);
return dp[i][j];
}
}

// Minimum Path Falling Sum;

class Solution {
public int minFallingPathSum(int[][] grid) {

int[][] dp = new int[grid.length][grid.length];

for (int i = 0; i < dp.length; i++) {
for (int j = 0; j < dp[0].length; j++) {
dp[i][j] = -1;
}
}
int CurSum = Integer.MAX_VALUE;

for (int i = 0; i < grid.length; i++) {
CurSum = Math.min (f (0, i, grid, dp), CurSum);
//System.out.println(CurSum);
}
return CurSum;
}
static int f (int i, int j, int[][] grid, int[][] dp) {

if (i == grid.length - 1 && (j >= 0 && j <= grid.length - 1) ){
return grid[i][j];
}

if (i >= grid.length || j >= grid.length || j < 0) {
return Integer.MAX_VALUE;
}

if (dp[i][j] != -1) {
return dp[i][j];
}

int same = f (i + 1, j, grid, dp);
int left = f (i + 1, j - 1, grid, dp);
int right = f (i + 1, j + 1, grid, dp);

int res = Math.min (same, left);

dp[i][j] = grid[i][j] + Math.min (res, right);
return dp[i][j];
}
}