AlgoMaster Logo

Game of Life

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Basic Simulation

Intuition:

The problem involves updating the board according to the rules given, where a cell's next state is conditioned by its current state and the states of its eight neighbors. A straightforward approach is to create a copy of the board to hold the previous state, which can be referenced while we iterate over the original board to apply the game rules.

Code:

2. In-Place State Tracking

Intuition:

To optimize space usage, we can encode information about both current and next states in the same board. By using integer encoding, we can keep the board's state transitions in a single space. For instance, we can use different integers to represent current and next states:

  • 0 -> 0: 0 (Dead to Dead)
  • 1 -> 1: 1 (Live to Live)
  • 1 -> 0: 2 (Live to Dead)
  • 0 -> 1: 3 (Dead to Live)

Code: