All problems
0999MediumArrayMatrixSimulation

One Tick of a Lamp Grid

Tracked in this browser only
Write code

Trains the technique from

LeetCode 289Game of Life

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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