Skip to main content
Back to problems
#289
Medium Algorithms

Game of life

Array Matrix Simulation
72.4% acceptance
Jan 12, 2026
6802
615
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state of the board is determined by applying the above rules simultaneously to every cell in the current state of the m x n grid board. In this process, births and deaths occur simultaneously. Given the current state of the board, update the board to reflect its next state. Note that you do not need to return anything.

Solution

Rust
Time O(n³)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn game_of_life(board: &mut Vec<Vec<i32>>) {
    let m = board.len();
    let n = board[0].len();
    
    for i in 0..m {
      for j in 0..n {
        let mut live_neighbors = 0;
        
        for di in -1..=1 {
          for dj in -1..=1 {
            if di == 0 && dj == 0 {
              continue;
            }
            let ni = i as i32 + di;
            let nj = j as i32 + dj;
            if ni >= 0 && ni < m as i32 && nj >= 0 && nj < n as i32 {
              if board[ni as usize][nj as usize] & 1 == 1 {
                live_neighbors += 1;
              }
            }
          }
        }
        
        if board[i][j] == 1 && (live_neighbors == 2 || live_neighbors == 3) {
          board[i][j] = 3;
        } else if board[i][j] == 0 && live_neighbors == 3 {
          board[i][j] = 2;
        }
      }
    }
    
    for i in 0..m {
      for j in 0..n {
        board[i][j] >>= 1;
      }
    }
  }
}