Show problems as
Classic problem #289MediumArrayMatrixSimulation

Game of Life

Real-world version: One Tick of a Lamp Grid
Tracked in this browser only
Read Game of Life on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A display panel holds lamps, each either lit as 1 or dark as 0. A lamp's neighbours are the cells touching it along an edge or at a corner, so up to eight of them.

On one tick every lamp changes at the same instant, and each one looks only at how many of its neighbours were lit just before the tick:

  • a lit lamp with fewer than two lit neighbours goes dark;
  • a lit lamp with two or three lit neighbours stays lit;
  • a lit lamp with more than three lit neighbours goes dark;
  • a dark lamp with exactly three lit neighbours comes on.

Return the panel as it stands after one tick.

Examples

Example 1

Input
panel = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]
Output
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]

The middle lamp of the lit row keeps two lit neighbours and holds. The two ends have only one each and go dark. The cells straight above and below the middle each touch all three lit lamps, so they come on, leaving the row standing upright.

Example 2

Input
panel = [[1, 1], [1, 1]]
Output
[[1, 1], [1, 1]]

Each lamp touches the other three, so every one of them has three lit neighbours and stays lit. Nothing changes.

Example 3

Input
panel = [[0, 1, 0], [1, 1, 0], [0, 0, 1]]
Output
[[1, 1, 0], [1, 1, 1], [0, 1, 0]]

The dark top-left cell touches three lit lamps and comes on. The lit lamp in the bottom-right corner touches only one and goes out. Two more dark cells, the one right of centre and the one below centre, each touch exactly three lit lamps and come on.

Constraints

  • 1 <= panel.length <= 25
  • 1 <= panel[i].length <= 25
  • 0 <= panel[i][j] <= 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def game_of_life(panel: list[list[int]]) -> list[list[int]]:
Java
public int[][] gameOfLife(int[][] panel)