Question - 1219. Path with Maximum Gold ( https://leetcode.com/problems/path-with-maximum-gold/)
Can you please tell the difference between both the given Code?
'''
// This Code is working Fine
public int getMaximumGold(int[][] grid,int row,int column,int [][] path) {
if(row<0||column<0||row>=grid.length||column>=grid[row].length){
return 0;
}
if(path[row][column]==1||grid[row][column]==0){
return 0;
}
path[row][column]=1;
int ans1= grid[row][column]+getMaximumGold(grid,row,column+1,path);;
int ans2=grid[row][column]+getMaximumGold(grid,row,column-1,path);
int ans3=grid[row][column]+getMaximumGold(grid,row-1,column,path);
int ans4=grid[row][column]+getMaximumGold(grid,row+1,column,path);
** path[row][column]=0;**// **Here we make the path 0 again**
return Math.max(ans1,Math.max(ans2,Math.max(ans3,ans4)));
}
public int getMaximumGold(int[][] grid) {
int path[][]= new int[grid.length][grid[0].length];
int max=0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
if(grid[i][j]!=0){
int ans= getMaximumGold(grid,i,j,path);
//System.out.println(i+" "+j+" "+ans);
max=Math.max(max,ans);
}
}
}
return max;
}'''
// The below given is code is similar to above the only difference is that instead making path[][]=0 again (path[row][column]=0;) , I make new array for each call .
'''
// This code is not Working
public int getMaximumGold(int[][] grid,int row,int column,int [][] path) {
if(row<0||column<0||row>=grid.length||column>=grid[row].length){
return 0;
}
if(path[row][column]==1||grid[row][column]==0){
return 0;
}
path[row][column]=1;
int ans1= grid[row][column]+getMaximumGold(grid,row,column+1,path);;
int ans2=grid[row][column]+getMaximumGold(grid,row,column-1,path);
int ans3=grid[row][column]+getMaximumGold(grid,row-1,column,path);
int ans4=grid[row][column]+getMaximumGold(grid,row+1,column,path);
return Math.max(ans1,Math.max(ans2,Math.max(ans3,ans4)));
}
public int getMaximumGold(int[][] grid) {
int max=0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
if(grid[i][j]!=0){
//**Making new array for each Call**
int path[][]= new int[grid.length][grid[i].length];
int ans= getMaximumGold(grid,i,j,path);
max=Math.max(max,ans);
}
}
}
return max;
}'''