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
            }
        }
    }
};
 

 
    
Top comments (0)