|
| 1 | +/** |
| 2 | + * 957. Prison Cells After N Days |
| 3 | + * https://leetcode.com/problems/prison-cells-after-n-days/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are 8 prison cells in a row and each cell is either occupied or vacant. |
| 7 | + * |
| 8 | + * Each day, whether the cell is occupied or vacant changes according to the following rules: |
| 9 | + * - If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell |
| 10 | + * becomes occupied. |
| 11 | + * - Otherwise, it becomes vacant. |
| 12 | + * |
| 13 | + * Note that because the prison is a row, the first and the last cells in the row can't have two |
| 14 | + * adjacent neighbors. |
| 15 | + * |
| 16 | + * You are given an integer array cells where cells[i] == 1 if the ith cell is occupied and |
| 17 | + * cells[i] == 0 if the ith cell is vacant, and you are given an integer n. |
| 18 | + * |
| 19 | + * Return the state of the prison after n days (i.e., n such changes described above). |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} cells |
| 24 | + * @param {number} n |
| 25 | + * @return {number[]} |
| 26 | + */ |
| 27 | +var prisonAfterNDays = function(cells, n) { |
| 28 | + const nextState = cells => [ |
| 29 | + 0, |
| 30 | + ...Array.from({ length: 6 }, (_, i) => cells[i] === cells[i + 2] ? 1 : 0), |
| 31 | + 0 |
| 32 | + ]; |
| 33 | + |
| 34 | + let current = [...cells]; |
| 35 | + const seen = new Map(); |
| 36 | + let cycleLength = 0; |
| 37 | + |
| 38 | + while (n > 0) { |
| 39 | + const stateKey = current.join(''); |
| 40 | + if (seen.has(stateKey)) { |
| 41 | + const cycleStart = seen.get(stateKey); |
| 42 | + cycleLength = cycleStart - n; |
| 43 | + n %= cycleLength; |
| 44 | + } |
| 45 | + seen.set(stateKey, n); |
| 46 | + if (n > 0) { |
| 47 | + current = nextState(current); |
| 48 | + n--; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + return current; |
| 53 | +}; |
0 commit comments