Notes

Personal notes on various topics

View on GitHub

Game of Life

Problem Statement

Conway’s Game of Life is a cellular automaton played on an m x n grid of cells, where each cell is either live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, and diagonal) according to these rules:

  1. Any live cell with fewer than two live neighbors dies (under-population).
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies (over-population).
  4. Any dead cell with exactly three live neighbors becomes a live cell (reproduction).

All cells are updated simultaneously based on the current state.

Task:
Given the current state of the board as a 2D array, update the board to its next state according to the rules above. You do not need to return anything; update the board in-place.

Examples:

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

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

Constraints:

Follow-up:
Can you solve it in-place, ensuring all cells are updated simultaneously? How would you handle the infinite board scenario when live cells reach the border?

Code Template

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        # Your code here
        pass

Solutions

Back to Problem List Back to Categories