Problem 289

Abstract / Summary

Given a board of cells with certain states next states are computed based on neighbor counts without using extra space.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0289.cpp

class Solution {
public:
    void gameOfLife(vector<vector<int>>& board) {
        int width  = board.size();
        int height = board[0].size();

        vector<vector<int>> next(width, vector<int>(height, 0));
        for (int x = 0; x < width; x++)
            for (int y = 0; y < height; y++)
            {
                int neighbors = 0;
                if (x > 0 && y > 0)
                    neighbors += board[x-1][y-1];
                if (x > 0)
                    neighbors += board[x-1][y];
                if (x > 0 && y < height - 1)
                    neighbors += board[x-1][y+1];
                if (y > 0)
                    neighbors += board[x][y-1];
                if (y < height - 1)
                    neighbors += board[x][y+1];
                if (x < width - 1 && y > 0)
                    neighbors += board[x+1][y-1];
                if (x < width - 1)
                    neighbors += board[x+1][y];
                if (x < width - 1 && y < height - 1)
                    neighbors += board[x+1][y+1];

                if (board[x][y] == 0)
                {
                    if (neighbors == 3)
                        next[x][y] = 1;
                }
                else
                {
                    if (neighbors == 2 || neighbors == 3)
                        next[x][y] = 1;
                }
            }

        board = next;
    }
};
43 lines | 1442 bytes | submitted August 22, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (800k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation provides a method to evolve a two-dimensional cellular automaton according to the classic Game of Life rules. It receives a mutable grid, computes the next generation in a separate matrix, and finally replaces the original grid with the newly computed state. The algorithm iterates over every cell, counts live neighbours by inspecting up to eight adjacent positions, applies the survival and birth conditions, and stores the result in an auxiliary structure before copying it back.

Key Steps

The first step extracts the dimensions of the input grid. The width corresponds to the number of rows, while the height corresponds to the number of columns in the first row.

int width  = board.size();
int height = board[0].size();

Next, an auxiliary matrix next of identical size is allocated and initialized with zeros. This matrix holds the state of the board after applying the transition rules, ensuring that updates do not interfere with neighbour calculations for cells that have not yet been processed.

vector<vector<int>> next(width, vector<int>(height, 0));

The core of the algorithm consists of a double nested loop that visits each cell (x, y). For each cell, a neighbour counter is reset to zero. The code then examines each of the eight possible neighbour positions, adding the value of the neighbour cell to the counter only when the neighbour lies inside the bounds of the board. Boundary checks (x > 0, y < height - 1, etc.) guard against out-of-range accesses, effectively handling edge and corner cells without special-case logic elsewhere.

for (int x = 0; x < width; x++)
    for (int y = 0; y < height; y++)
    {
        int neighbors = 0;
        if (x > 0 && y > 0)
            neighbors += board[x-1][y-1];
        if (x > 0)
            neighbors += board[x-1][y];
        if (x > 0 && y < height - 1)
            neighbors += board[x-1][y+1];
        if (y > 0)
            neighbors += board[x][y-1];
        if (y < height - 1)
            neighbors += board[x][y+1];
        if (x < width - 1 && y > 0)
            neighbors += board[x+1][y-1];
        if (x < width - 1)
            neighbors += board[x+1][y];
        if (x < width - 1 && y < height - 1)
            neighbors += board[x+1][y+1];

After counting neighbours, the algorithm applies the Game of Life transition rules. If the current cell is dead (0) and exactly three neighbours are alive, the cell becomes alive in the next generation. If the cell is alive (1), it remains alive only when it has two or three live neighbours. The result is written into the corresponding position of the next matrix.

        if (board[x][y] == 0)
        {
            if (neighbors == 3)
                next[x][y] = 1;
        }
        else
        {
            if (neighbors == 2 || neighbors == 3)
                next[x][y] = 1;
        }
    }

Finally, the original board reference is replaced with the computed next matrix, completing the transition to the next generation.

board = next;

Edge Cases Handled

The neighbour-counting logic incorporates explicit boundary checks for each of the eight directions. When a cell resides on the top row (x == 0), the checks x > 0 prevent attempts to read rows above the board. Similarly, cells on the bottom row (x == width - 1) are protected by x < width - 1. The same pattern applies to the leftmost column (y == 0) and rightmost column (y == height - 1). These guards ensure that corner cells, which have only three neighbours, and edge cells, which have five neighbours, are processed correctly without accessing invalid memory. The initialization of the auxiliary matrix with zeros also guarantees that cells that do not satisfy the birth or survival conditions remain dead in the next state.

Performance Optimizations

The algorithm avoids in-place updates that would corrupt neighbour information during iteration. By allocating a separate next matrix, it guarantees that each neighbour lookup reads from the original, unchanged board, eliminating the need for additional bookkeeping or temporary markers. The use of simple integer addition for neighbour accumulation, rather than more complex data structures, keeps the inner loop lightweight. Boundary checks are performed inline with neighbour accesses, avoiding function calls or extra loops. The final assignment board = next leverages move semantics of the standard library container, allowing the underlying storage to be transferred efficiently without element-wise copying. This combination of a single pass over the grid, direct neighbour access, and efficient container reassignment yields a solution that scales well with board size while maintaining clear and maintainable code.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant checkerboard where little living cells live in each square. Some squares have a cell inside, and some squares are empty. This code is like a magical rulebook that decides what happens to the cells when a new day starts. Every cell looks at its eight neighbors to see how many friends are standing next to it.

If a square is empty, it needs exactly three neighbors to sprout a new little cell. If a square already has a cell, it stays happy and keeps living if it has two or three neighbors to play with. If it has too few neighbors, it gets lonely and disappears. If it has too many neighbors, it gets crowded and also disappears. The code goes through every square on the board one by one, counts the neighbors for each spot, and fills out a brand new board for the next day based on those rules. Once it finishes looking at every square, the old board is replaced by the new one, and the whole cycle is ready to start all over again.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.11 | σ = 1.13

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# Rust Java Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
Garvit244 Python
haoel C++
JoshCrozier JS
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
Garvit244 Python
haoel C++
JoshCrozier JavaScript
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
YuriSpiridonov Python
zfang399 C++
46 links | 30 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Game of Life - Leetcode 289 - Python'
NeetCode 18 mins
Game of Life - Leetcode 289 - Python
YouTube video 'Game of Life | Leetcode 289 | Matrix | Day-12'
Ayushi Sharma 20 mins
Game of Life | Leetcode 289 | Matrix | Day-12
YouTube video 'Game of Life | game of life | leetcode 289 | matrix | In-Place'
Naresh Gupta 13 mins
Game of Life | game of life | leetcode 289 | matrix | In-Place
YouTube video 'LeetCode 289. Game of Life - Interview Prep Ep 80'
Fisher Coder 14 mins
LeetCode 289. Game of Life - Interview Prep Ep 80
YouTube video 'Game of Life | Live Coding with Explanation | Leetcode - 289'
Algorithms Made Easy 9 mins
Game of Life | Live Coding with Explanation | Leetcode - 289
YouTube video 'Leetcode - Game of Life (Python)'
Timothy H Chang 13 mins
Leetcode - Game of Life (Python)
YouTube video 'LeetCode 289. Game of Life Explanation and Solution'
happygirlzt 10 mins
LeetCode 289. Game of Life Explanation and Solution
YouTube video 'Game of Life | Java | LeetCode Solution 289'
Tech Tutor 18 mins
Game of Life | Java | LeetCode Solution 289
YouTube video 'Game of Life | Leetcode 289  | Matrix  2D πŸ”₯πŸ”₯ | Live coding session'
Coding Decoded 12 mins
Game of Life | Leetcode 289 | Matrix 2D πŸ”₯πŸ”₯ | Live coding session
YouTube video 'LeetCode 289. Game of Life δΈ­ζ–‡θ§£ι‡Š'
happygirlzt 10 mins
LeetCode 289. Game of Life δΈ­ζ–‡θ§£ι‡Š
YouTube video 'Game of Life | Leetcode 289 | Leetcode December Challenge Day30 | Live Coding session'
Coding Decoded 16 mins
Game of Life | Leetcode 289 | Leetcode December Challenge Day30 | Live Coding session
YouTube video 'Daily Leetcode #742: Apr 12, 2022 - 289. Game of Life'
Programming Live with Larry 18 mins
Daily Leetcode #742: Apr 12, 2022 - 289. Game of Life
YouTube video 'LeetCode 289. Game of Life'
Happy Coding 16 mins
LeetCode 289. Game of Life
YouTube video 'Daily Leetcode #274: Dec 30, 2020 - 289. Game of Life'
Programming Live with Larry 13 mins
Daily Leetcode #274: Dec 30, 2020 - 289. Game of Life
YouTube video 'LeetCode 289: Game of Life | Java Solution | In-place Array Manipulation'
Code Scribbler 8 mins
LeetCode 289: Game of Life | Java Solution | In-place Array Manipulation
YouTube video 'Leetcode 289: Game of Life'
Algorithms Casts 21 mins
Leetcode 289: Game of Life
YouTube video 'Leetcode Question 289 "Game of Life" in Java'
Ghumman Tech 17 mins
Leetcode Question 289 "Game of Life" in Java
YouTube video 'Microsoft Coding Interview Question | Leetcode 289 | Game of Life'
WorkWithGoogler 6 mins
Microsoft Coding Interview Question | Leetcode 289 | Game of Life
YouTube video 'Day 208: LeetCode Problem 289.  Game of Life - Swift'
iOSxBank 20 mins
Day 208: LeetCode Problem 289. Game of Life - Swift
YouTube video 'LeetCode 289: Game of Life | Python Solution | In-place Matrix Manipulation'
Code Scribbler 8 mins
LeetCode 289: Game of Life | Python Solution | In-place Matrix Manipulation
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 5 medium
9 solutions   August 22, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality