Published
- 2 min read
Rotting Oranges
Given a m*n matrix of rotten oranges print time it takes to rotten all the oranges
0 representing an empty cell, 1 representing a fresh orange, 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent 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.
- This problem can be solved using BFS
- Check if the non diagonal cells are 1, we need to rotten them as they are directly reachable from the parent cell
- Each time we have rotten all the non diagonal neighbours we need to increment the number of minutes elapsed.
private int rottenOranges(int [][] arr) {
int [][] directions = {{0,-1}, {-1,0},{0,1},{1,0}}; //This is the final because it doesnt consider the diagonal
/*
* if we find a rotten orange and we should move not diagonal but only 4 other sides and consider them as neighbour
* add them to the queue and move from there
* think about the logic what would you do if anyone reachable node is still left with 1
*/
int rottenMinutes = 0;
boolean hasRotten = false;
boolean [][] visited = new boolean[arr.length][arr.length];
Queue<Integer []> queue = new LinkedList<>();
if(arr[0][0] != 2) {
System.out.println("There are no rotten oranges to begin with");
return -1;
}
queue.add(new Integer[]{0,0});
while(!queue.isEmpty()){
hasRotten = false;
Integer [] element = queue.poll();
int row = element[0];
int col = element[1];
for (int [] edges : directions) {
int newRow = row + edges[0];
int newCol = col + edges[1];
if(newRow < 0 || newCol < 0 || newRow >=arr.length || newCol >= arr.length) {
continue;
}
if(arr[newRow][newCol] == 1 && visited[newRow][newCol] == false) {
queue.add(new Integer[]{newRow, newCol});
visited[newRow][newCol] = true;
hasRotten = true;
arr[newRow][newCol] = 2;
}
}
if(hasRotten){
rottenMinutes++;
}
}
for (int i=0; i< arr.length; i++){
for (int j=0; j<arr.length; j++){
if(arr[i][j]==1){
return -1;
}
}
}
return rottenMinutes;
}
Key takeaways
- Look at the data structures used in the code above, arrays are used because they are fixed length hence memory footprint is also fixed.
- Look at the optimizations done in the code, no storing the neighbours and computing them on the fly
- Check conditions to find out how they are marked as rotten, check calculation of rottenMinutes
- Most important, read the constraints in the question accurately to find out what are the edge Conditions