I am working on the rotten oranges problem:
In a given grid, each cell can have one of three values:
- the value 0 representing an empty cell;
- the value 1 representing a fresh orange;
- the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten.
Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead.
Example 1:
- Input: [[1,1,1],[1,1,0],[0,1,2]]
- Output: 4
I've implemented a BFS solution. Then after finishing the BFS, I initiate another iteration to make sure that there's no fresh orange left, because if there are fresh oranges left over, then I have to return -1.
However, I find that in that final loop only some of the values were changed into 2, and some others remain at 1. I'm not sure why they are not changed to 2 as well.
class Solution {
public int orangesRotting(int[][] grid) {
//need adjacency list/matrix
Queue<String> q = new LinkedList<>();
int[] count = new int[1];
count[0] = 0;
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
if(grid[i][j] == 2) {
q.add("" + i + j);
bfs(grid, i, j, count, q);
}
}
}
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
// does NOT always print correct value: 1 is not changed to 2
System.out.println(grid[i][j]);
if(grid[i][j] == 1) {
return -1; // ... and so this -1 is returned when it shouldn't
}
}
}
return count[0];
}
private static void bfs(int[][] grid, int i, int j, int[] count, Queue<String> q) {
while(!q.isEmpty()) {
String s = q.remove();
//System.out.println(s); //prints correct indices
i = Integer.parseInt(s.substring(0,1));
j = Integer.parseInt(s.substring(1));
if(i - 1 > 0 && grid[i - 1][j] == 1) {
count[0]++;
i--;
grid[i][j] = 2;
q.add("" + i + j);
}
if(i + 1 < grid.length && grid[i + 1][j] == 1) {
count[0]++;
i++;
grid[i][j] = 2;
q.add("" + i + j);
}
if(j - 1 > 0 && grid[i][j - 1] == 1) {
count[0]++;
j--;
grid[i][j] = 2;
q.add("" + i + j);
}
if(j + 1 < grid.length && grid[i][j + 1] == 1) {
count[0]++;
j++;
grid[i][j] = 2;
q.add("" + i + j);
}
}
}
}
My code outputs -1 for the above quoted example, because it still finds a 1 in the final loop, while it shouldn't.
Could you help me figure out why this is happening?