> Uploading knowledge... _
[░░░░░░░░░░░░░░░░░░░░░░░░] 0%
blog logo
> CHICIO CODING_Pixels. Code. Unplugged.

Game of Life

Leetcode Problem 289: Game of Life

Problem Summary

The m × n Game of Life board consists of cells that are either alive (1) or dead (0). Each cell interacts simultaneously with its 8 neighbors (horizontal, vertical, and diagonal). Apply the following rules to determine the board's next state:

  1. A live cell with fewer than 2 live neighbors dies (underpopulation).
  2. A live cell with 2 or 3 live neighbors survives to the next generation.
  3. A live cell with more than 3 live neighbors dies (overpopulation).
  4. A dead cell with exactly 3 live neighbors becomes alive (reproduction).

Update the board in-place to reflect its next state. All transitions must happen simultaneously based on the current state.

Constraints:

  • The board dimensions m and n are each between 1 and 25.
  • Each cell value is either 0 (dead) or 1 (alive).

Techniques

  • Array
  • Matrix
  • Simulation

Solution

/**
 Do not return anything, modify board in-place instead.
 */

 enum CellStatus {
    dead = 0,
    alive = 1,
    aliveToDead = 2,
    deadToAlive = 3
}

function gameOfLife(board: number[][]): void {
    for (let i = 0; i < board.length; i++) {
        for (let h = 0; h < board[i].length; h++) {
            
            let aliveCells = 0

            for (let k = i - 1; k <= i + 1; k++) {
                for (let j = h - 1; j <= h + 1; j++) {
                    if (k < 0 || j < 0 || k >= board.length || j >= board[i].length || (i == k && j === h)) {
                        continue
                    }

                    if (board[k][j] === CellStatus.aliveToDead || board[k][j] === CellStatus.alive) {
                        aliveCells++
                    }
                }
            }

            if ((aliveCells < 2 || aliveCells > 3) && (board[i][h] === CellStatus.alive || board[i][h] === CellStatus.aliveToDead)) {
                board[i][h] = CellStatus.aliveToDead
            } else if (aliveCells === 3 && (board[i][h] === 0 || board[i][h] === 3)) {
                board[i][h] = CellStatus.deadToAlive
            }
        }
    }

    for (let i = 0; i < board.length; i++) {
        for (let h = 0; h < board[i].length; h++) {
            board[i][h] = board[i][h] % 2
        }
    }
};


console.log(gameOfLife([[0,1,0],[0,0,1],[1,1,1],[0,0,0]]))
console.log(gameOfLife([[1,1],[1,0]]))