Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Problem: Time taken by tomatoes to rot in JavaScript
Problem
We are required to write a JavaScript function that takes in a 2-D array of numbers, arr, as the only argument.
The numbers in the array can be −
the value 0 which represents an empty cell;
the value 1 which represents a fresh tomato;
the value 2 which represents a rotten tomato.
Every minute, any fresh tomato that is adjacent (4-directionally) to a rotten tomato becomes rotten.
Our function is supposed to return the minimum number of minutes that must elapse until no cell has a fresh tomato. If this is impossible, we should return -1 instead.
For example, if the input to the function is −
const arr = [ [2, 1, 1], [1, 1, 0], [0, 1, 1] ];
Then the output should be −
const output = 4;
Output Explanation
| Time Elapsed | Tomatoes status |
|---|---|
| 1 | [ [2, 2, 1], [2, 1, 0], [0, 1, 1] ] |
| 2 | [ [2, 2, 2], [2, 2, 0], [0, 1, 1] ] |
| 3 | [ [2, 2, 2], [2, 2, 0], [0, 2, 1] ] |
| 4 | [ [2, 2, 2], [2, 2, 0], [0, 2, 2] ] |
Example
The code for this will be −
const arr = [
[2, 1, 1],
[1, 1, 0],
[0, 1, 1]
];
const timeToRot = (arr = []) => {
let fresh = 0;
let count = -1;
let curr = [];
for(let i = 0; i < arr.length; i++){
for(let j = 0; j < arr[i].length; j++){
if(arr[i][j] === 1){
fresh += 1;
};
if(arr[i][j] === 2){
curr.push([i, j]);
};
};
};
if(!fresh){
return 0;
};
while(curr.length > 0){
count += 1;
const next = [];
const rotten = (i, j) => {
arr[i][j] = 2
next.push([i, j])
fresh -= 1
};
for(const [i, j] of curr){
if (arr[i - 1] && arr[i - 1][j] === 1) {
rotten(i - 1, j);
};
if (arr[i + 1] && arr[i + 1][j] === 1) {
rotten(i + 1, j);
};
if (arr[i][j - 1] === 1) {
rotten(i, j - 1);
};
if (arr[i][j + 1] === 1) {
rotten(i, j + 1);
};
}
curr = next
};
return fresh === 0 ? count : -1;
};
console.log(timeToRot(arr));
Output
And the output in the console will be −
4
Advertisements