DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 289. Game of Life

Cell State Mapping:

Original State New State Transitional Value Meaning
1 (Alive) 0 (Dead) 2 Cell was alive but will die.
0 (Dead) 1 (Alive) 3 Cell was dead but will become alive.
1 (Alive) 1 (Alive) 1 Cell remains alive.
0 (Dead) 0 (Dead) 0 Cell remains dead.

This clearly shows how each original state transitions using the intermediate values.

const countNeighbours = (r, c, board) => {
    const ROWS = board.length;
    const COLS = board[0].length;
    let count = 0;
    const directions = [
        [0, 1], [1, 0], [0, -1], [-1, 0],  // Horizontal and vertical directions
        [1, 1], [1, -1], [-1, 1], [-1, -1] // Diagonal directions
    ];

    for (const [dr, dc] of directions) {
        const nr = r + dr;
        const nc = c + dc;
        // Only count originally alive cells (1 or 2)
        if (nr >= 0 && nr < ROWS && nc >= 0 && nc < COLS) {
            if (board[nr][nc] === 1 || board[nr][nc] === 2) {
                count++;
            }
        }
    }

    return count;
};

var gameOfLife = function (board) {
    const ROWS = board.length;
    const COLS = board[0].length;

    // First pass: Mark cells with transitional states
    for (let r = 0; r < ROWS; r++) {
        for (let c = 0; c < COLS; c++) {
            const nei = countNeighbours(r, c, board); // Count live neighbors

            if (board[r][c] === 1) {
                // Alive cell: stays alive with 2 or 3 neighbors, else dies
                if (nei < 2 || nei > 3) {
                    board[r][c] = 2; // Alive ā†’ Dead
                }
            } else if (board[r][c] === 0) {
                // Dead cell: becomes alive if exactly 3 neighbors
                if (nei === 3) {
                    board[r][c] = 3; // Dead ā†’ Alive
                }
            }
        }
    }

    // Second pass: Finalize the board state
    for (let r = 0; r < ROWS; r++) {
        for (let c = 0; c < COLS; c++) {
            if (board[r][c] === 2) {
                board[r][c] = 0; // Mark dead
            } else if (board[r][c] === 3) {
                board[r][c] = 1; // Mark alive
            }
        }
    }
};

Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

šŸ‘‹ Kindness is contagious

DEV shines when you're signed in, unlocking a customized experience with features like dark mode!

Okay