Please help me in finding that where I am doing the mistake in this solution as my output is coming wrong. thanks in advance.
// making the recursive call to findMinCost by reducing the row and column and finding the min cost out of that
public static int findMinCost(int[][] maze, int row, int col) {
if(row == 0 && col == 0) {
return maze[row][col];
}
int cost = 0;
if(row >= 0 && col >=0) {
cost += Integer.min(findMinCost(maze, row-1, col),findMinCost(maze, row, col-
1))+maze[row][col];
}
return cost;
}
The main problem is that when one or both of the coordinates become negative (and this will happen), your function returns 0 as cost. This is not correct, as zero might be an interesting cost to go for. In this case a search is made outside the maze and that should be made impossible: so return an extreme high cost in that case, not 0.
The fix is simple: add an else
block to your second if
block:
} else return Integer.MAX_VALUE;
Now it will work for small mazes. (I assume you correctly call your function with row
and col
referencing the bottom-right cell in the maze)
For larger mazes you will run into a timing problem, since this algorithm will revisit the same sub-paths over and over again. You can solve this by using memoization.