Game of Life

Medium#289old and new in one cell

You get a board of cells, 1 alive and 0 dead. Work out the next generation, all cells at once, in place. Each cell looks at its up to eight neighbours: an alive cell with 2 or 3 alive neighbours lives on, with fewer or more it dies; a dead cell with exactly 3 comes alive. Our example: [0, 0, 0], [1, 1, 1], [0, 0, 0] → [0, 1, 0], [0, 1, 0], [0, 1, 0].

input
board: an m × n grid of cells, 1 alive and 0 dead. Each cell has up to eight neighbours: the cells beside it, above, below and on the diagonals.
returns
Nothing: change board in place into the next generation, every cell at once. A live cell with two or three live neighbours lives on, any other live cell dies; a dead cell with exactly three live neighbours comes alive.
constraints
  • 1 ≤ m, n ≤ 25, board[i].length = n
  • board[i][j] is 0 or 1
our 14 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} board
 * @return {void} Do not return anything, modify board in-place instead.
 */
function gameOfLife(board) {

}
Ctrl ↵
format
reset

saved in this browser

14 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more matrix traversal problems

Pattern “Matrix traversal” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.