Game of Life

Medium · Matrix · Array · Matrix · Simulation

Problem

You are given an m x n board for Conway’s Game of Life, where 1 is a live cell and 0 a dead one. Each cell has up to eight neighbors (horizontal, vertical and diagonal). The next generation is computed from the current one, for all cells at once:

Update board in place to its next state. Every decision must use the neighbor counts of the current generation, not values you have already updated. Your function returns nothing; the tests check board after the call.

Examples

Input: board = [[0,1,0],[0,1,0],[0,1,0]]
Output: [[0,0,0],[1,1,1],[0,0,0]]

A vertical blinker turns horizontal: the ends die and the middle row’s side cells are born.

Input: board = [[1,1,0],[1,0,0],[0,0,0]]
Output: [[1,1,0],[1,1,0],[0,0,0]]

The dead cell (1,1) has three live neighbors and is born; each of the three live cells has two live neighbors and survives.

Constraints

Approaches

Follow-up

What if the board is unbounded, or huge and mostly empty? Store only the live cells in a set and count neighbors with a dictionary (see the use case “Live cells on an unbounded plane after k steps”). And if the edges wrap around, use (r + dr) % m.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…