Engineering platform~20 min2s · 256 MBtarget O(m * n) time, O(m * n) spaceclassic twin: lc-289traversal
A data hall is a grid of racks. A cell is 1 when the rack runs jobs and 0 when it is idle. A scheduler moves load at the same moment on every rack, using only what its eight neighbours were doing a moment earlier.
A running rack with fewer than 2 running neighbours is idle in the next step, because it has too little work to share. With more than 3 running neighbours it is idle too, because it is overloaded.
A running rack with 2 or 3 running neighbours keeps running. An idle rack with exactly 3 running neighbours starts running. Places outside the hall count as idle. Halls reach 200 by 200 racks.
Write next_generation(cells).
cells[r][c] is 1 when the rack in row r and place c runs, and 0 when it is idle.Input: cells = [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
Output: [[0, 0, 0], [1, 1, 1], [0, 0, 0]]The middle column runs and the rest is idle. The table shows the number of running neighbours of each rack.
| Row | Place 0 | Place 1 | Place 2 |
|---|---|---|---|
| 0 | 2 | 1 | 2 |
| 1 | 3 | 2 | 3 |
| 2 | 2 | 1 | 2 |
The middle rack has 2 running neighbours and stays running. The racks beside it have 3 and start. The top and bottom racks have 1 and stop.
Input: cells = [[1, 1], [1, 1]]
Output: [[1, 1], [1, 1]]Each rack has 3 running neighbours and keeps running, so the hall does not change.
Input: cells = [[0, 0], [0, 0]]
Output: [[0, 0], [0, 0]]An idle hall stays idle.
1 ≤ cells.length ≤ 200 (rows)1 ≤ cells[r].length ≤ 200 (places in a row, the same for every row)cells[r][c] is 0 or 1There are 40,000 racks. Scanning the whole hall to find the neighbours of each rack reads 1,600,000,000 cells.
A rack has at most 8 neighbours at fixed offsets, so 8 reads per rack are enough: 320,000 reads.