11 · Matrices & Simulation

#289 Game of Life

Mediumsolve on LeetCode ↗

frequently reported atMicrosoftAmazonGoogle

the problem

In plain words

An m × n board is one generation of Conway's Game of Life: 1 means alive, 0 means dead. Each cell looks at its 8 neighbours (sides and corners; there is nothing beyond the edges). A live cell with 2 or 3 live neighbours stays alive, and with any other count it dies. A dead cell with exactly 3 live neighbours comes alive. Every cell changes at the same moment. Replace the board with the next generation, in place.

in board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]

out [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]

This shape is the famous glider: on an endless board it travels one cell diagonally every 4 generations.

in board = [[1,1],[1,0]]

out [[1,1],[1,1]]

The dead corner has exactly 3 live neighbours, so it comes alive.

  • 1 ≤ m, n ≤ 25
  • board[i][j] is 0 or 1

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #73
      Set Matrix Zeroes
      Mediumin Matrices
    2. #994
      Rotting Oranges
      Mediumin Graphs
    3. #200
      Number of Islands
      Mediumin Graphs