Game of Life
Conway's Game of Life is played on an m x n board where each cell is either alive (1) or dead (0). Every cell has up to eight neighbors — horizontally, vertically, and diagonally adjacent — and the whole board updates at once, following these rules:
- A live cell with fewer than two live neighbors dies (underpopulation).
- A live cell with two or three live neighbors survives.
- A live cell with more than three live neighbors dies (overpopulation).
- A dead cell with exactly three live neighbors comes alive (reproduction).
Given the board's current state, compute its next state in place. Every transition must use the original board state.
Input Format
Implement gameOfLife(board). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Modify argument 1 in place. The editor compares its final value; the function return value is ignored.
Sample Input and Output
Example 1 · Run Sample
Input
board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]] Output
[[0,0,0],[1,0,1],[0,1,1],[0,1,0]] Example 2
Input
board = [[1]] Output
[[0]] Constraints
- 1 <= m, n <= 25
- board[i][j] is 0 or 1
Test Cases (2)
Case 1
Args: [[[0,1,0],[0,0,1],[1,1,1],[0,0,0]]]
Expected: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
Case 2
Args: [[[1]]]
Expected: [[0]]
Topics
To update in-place, encode transitions with extra states: 2 means alive → dead, 3 means dead → alive. Count live neighbors using original states (values 1 or 2), then do a final pass to map states back to 0/1.
function gameOfLife(board) {
const m = board.length, n = board[0].length;
const dirs = [-1, 0, 1];
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
let live = 0;
for (const di of dirs) {
for (const dj of dirs) {
if (di === 0 && dj === 0) continue;
const ni = i + di, nj = j + dj;
if (ni >= 0 && ni < m && nj >= 0 && nj < n) {
if (board[ni][nj] === 1 || board[ni][nj] === 2) live++;
}
}
}
if (board[i][j] === 1 && (live < 2 || live > 3)) board[i][j] = 2;
if (board[i][j] === 0 && live === 3) board[i][j] = 3;
}
}
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === 2) board[i][j] = 0;
if (board[i][j] === 3) board[i][j] = 1;
}
}
}Time: O(m × n) Space: O(1)
Saved in this browser only. Private to you.