I am trying to solve a LeetCode problem (1219. Path with Maximum Gold) with BFS approach
Statement:
In a gold mine grid of size m x n, each cell in this mine has an integer representing the amount of gold in that cell, 0 if it is empty. Return the maximum amount of gold you can collect under the conditions: Every time you are located in a cell you will collect all the gold in that cell. From your position, you can walk one step to the left, right, up, or down. You can't visit the same cell more than once. Never visit a cell with 0 gold. You can start and stop collecting gold from any position in the grid that has some gold.
class Solution {
public int getMaximumGold(int[][] grid) {
int max = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] != 0) {
boolean isVis[][] = new boolean[grid.length][grid[0].length];
int val = bfs(i, j, isVis, grid);
max = Math.max(max, val);
}
}
}
return max;
}
public int bfs(int r, int c, boolean isVis[][], int[][] grid) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[] { r, c, grid[r][c] });
int max = grid[r][c];
isVis[r][c] = true;
while (!q.isEmpty()) {
int path[] = q.poll();
int[][] arr = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (int i = 0; i < 4; i++) {
int rc = path[0] + arr[i][0];
int cc = path[1] + arr[i][1];
if (rc < 0 || cc < 0 || rc >= grid.length || cc >= grid[0].length || isVis[rc][cc]
|| grid[rc][cc] == 0) {
max = Math.max(max, path[2]);
continue;
}
int sum = grid[rc][cc] + path[2];
isVis[rc][cc] = true;
q.add(new int[] { rc, cc, sum });
}
}
return max;
}
}
I am able get execute 28 test case , the below one is failing
int grid[][] = {{1,0,7,0,0,0},{2,0,6,0,1,0},{3,5,6,7,4,2},{4,3,1,0,2,0},{3,0,5,0,20,0}};
Expected answer is 60 my code gives 54 I could not find the issue in my code. Any one could help on finding the issue with the above code