Skip to content

Instantly share code, notes, and snippets.

@madhur
Created June 5, 2019 05:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madhur/24d8ac1ac4b84f95980561874ef41a7d to your computer and use it in GitHub Desktop.
Save madhur/24d8ac1ac4b84f95980561874ef41a7d to your computer and use it in GitHub Desktop.
maximum matrix sum dfs
// java.util.* and java.util.streams.* have been imported for this problem.
// You don't need any other imports.
public static int matrixMaxSumDfs(int[][] grid) {
int[] sum = new int[1];
int answer = helper(grid, 0, 0, sum);
return answer;
}
private static int helper(int [][] matrix, int a, int b, int[] sum) {
int rows = matrix.length;
int cols = matrix[0].length;
if(a == rows || b==cols) {
return 0;
}
if(a==rows-1 && b==cols-1) {
return matrix[a][b];
}
int down = helper(matrix, a+1, b, sum);
int right = helper(matrix, a, b+1, sum);
if (down + matrix[a][b] > right + matrix[a][b]) {
return down + matrix[a][b];
}
return right + matrix[a][b];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment