Start learning free

LESSON 299 OF 635 · MATRIX

Game of Life in Python

Practice O(m · n)

You get a grid, board, with m rows and n columns. Each cell is 1 (live) or 0 (dead).

Change board in place into its next generation. Return nothing.

The neighbors of a cell are the cells that touch it, diagonals included. A cell has at most 8 of them. Cells on the edges have fewer.

Each cell's next state depends on how many live neighbors it has now:

  • A live cell with 2 or 3 live neighbors stays live.
  • A dead cell with exactly 3 live neighbors becomes live.
  • Every other cell is dead in the next generation.

All cells change at once. Always count the neighbors on the board as it was at the start.

The grid is a list of rows. Each row is a list of integers.

 

Example 1:

Input: board = [
  [0, 1, 0],
  [0, 1, 0],
  [0, 1, 0]
]
Output: [
  [0, 0, 0],
  [1, 1, 1],
  [0, 0, 0]
]
Explanation: The center has 2 live neighbors. It stays live.
The top and bottom live cells have 1 live neighbor each. They die.
The left and right cells of the middle row have 3. They become live.
The four corners have 2. They stay dead.

Example 2:

Input: board = [
  [1, 1, 1],
  [1, 1, 1],
  [1, 1, 1]
]
Output: [
  [1, 0, 1],
  [0, 0, 0],
  [1, 0, 1]
]
Explanation: Each corner has 3 live neighbors. It stays live.
Each cell in the middle of a side has 5. It dies.
The center has 8. It dies too.

Example 3:

Input: board = [
  [1, 0, 0, 1]
]
Output: [
  [0, 0, 0, 0]
]
Explanation: The board has one row.
The two live cells are at opposite ends. They are not neighbors.
Each has 0 live neighbors, so both die.

 

Constraints:

  • 1 to 300 rows.
  • 1 to 300 columns.
  • All rows have the same length.
  • Each cell is 0 or 1.

Note:

Your solution should run in O(m * n) time and use O(1) extra space.

STEP 1 OF 13
    Ctrl + Enter to check

    Game Of Life in Python

    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free