Game of Life - aloalgo

Game of Life

Medium

According to Conway's Game of Life, cells on a 2D board can be either live (1) or dead (0). Each cell interacts with its eight neighbours (horizontal, vertical, or diagonal). The game evolves based on four rules for the next generation:

  1. Any live cell with fewer than two live neighbours dies, as if by underpopulation.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overpopulation.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

The next generation is created by applying these rules simultaneously to every cell. This means that for a cell's neighbours, you must consider their current state (before any changes are applied across the board). Your task is to update the board in-place, modifying the given board directly. The function should then return the modified board.

Note: For this problem, assume the board boundaries mean cells outside the board do not exist as neighbors (i.e., treat the edges as boundaries, not wrapping).

Example 1

Input
[
  [1, 0, 1],
  [0, 1, 0],
  [1, 0, 1]
]
Output
[
  [0, 1, 0],
  [1, 0, 1],
  [0, 1, 0]
]
Explanation:

Initial board: [[1,0,1],[0,1,0],[1,0,1]]. Cell (0,0) (live) has 1 live neighbor, dies. Cell (0,1) (dead) has 3 live neighbors, becomes live. Cell (1,1) (live) has 4 live neighbors, dies. Other cells update based on rules. Final state after in-place modification would be [[0,1,0],[1,0,1],[0,1,0]].

Example 2

Input
[
  [0, 1],
  [1, 0]
]
Output
[
  [0, 0],
  [0, 0]
]
Explanation:

Initial board: [[0,1],[1,0]]. Cell (0,1) (live) has 1 live neighbor, so it dies. Cell (1,0) (live) has 1 live neighbor, so it dies. Cell (0,0) (dead) has 2 live neighbors, so it stays dead. Cell (1,1) (dead) has 2 live neighbors, so it stays dead. Final state after in-place modification would be [[0,0],[0,0]].

Example 3

Input
[
  [0, 0, 0, 0],
  [0, 1, 1, 0],
  [0, 1, 1, 0],
  [0, 0, 0, 0]
]
Output
[
  [0, 0, 0, 0],
  [0, 1, 1, 0],
  [0, 1, 1, 0],
  [0, 0, 0, 0]
]
Explanation:

Initial board: [[0,0,0,0],[0,1,1,0],[0,1,1,0],[0,0,0,0]]. All live cells (the 1s forming a 2x2 block) have exactly 3 live neighbors, so they remain alive. All dead cells have less than 3 live neighbors. This is a stable configuration (a 'still life' block). Final state after in-place modification would be [[0,0,0,0],[0,1,1,0],[0,1,1,0],[0,0,0,0]].

Loading...
Input
[
  [1, 0, 1],
  [0, 1, 0],
  [1, 0, 1]
]
Output
[
  [0, 1, 0],
  [1, 0, 1],
  [0, 1, 0]
]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!