問題:JavaScript 中番茄腐爛所需時間
問題
我們需要編寫一個 JavaScript 函式,它只接受一個二維數字陣列 arr 作為引數。
陣列中的數字可以是:
值 0,表示空單元格;
值 1,表示新鮮番茄;
值 2,表示腐爛番茄。
每分鐘,任何與腐爛番茄相鄰(四方向)的新鮮番茄都會腐爛。
我們的函式應該返回必須經過的最小分鐘數,直到沒有單元格包含新鮮番茄。如果這是不可能的,我們應該返回 -1。
例如,如果函式的輸入是:
const arr = [ [2, 1, 1], [1, 1, 0], [0, 1, 1] ];
那麼輸出應該是:
const output = 4;
輸出解釋
經過的時間 | 番茄狀態 |
---|---|
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] ] |
示例
這段程式碼將是:
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));
輸出
控制檯中的輸出將是:
4
廣告