I am trying to solve the following problem on leetcode.com
I found a resource asking a similar question but it didn't yield anything plausible.
I am able to come up with a recursive backtracking solution but it fails the last 5 test cases for a very large matrix. I sense there is some repetitive work but can't tell what it is.
The way the logic is written, I am struggling to find out
- What I need to memoize
- How to tailor my logic so that I am optimizing at each step
Any help is appreciated
class Solution {
private long max = -1;
public int maxProductPath(int[][] grid) {
long mod=1000000007;
int rows = grid.length;
int cols = grid[0].length;
int cp = 1;
pathFinder(grid, rows, cols, cp, rows-1, cols-1);
if(max < 0 ) return -1;
return (int)(max % mod);
}
public void pathFinder(int[][]grid, int rows, int cols, long cp, int r, int c){
if(r >= rows || c >= cols || r < 0 || c < 0){
return;
}
if(r == 0 && c == 0){
this.max = Math.max(cp * grid[r][c] , this.max);
return;
}
pathFinder(grid, rows, cols, cp * grid[r][c], r - 1, c);
pathFinder(grid, rows, cols, cp * grid[r][c], r , c - 1);
}
}