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;
}
};
Difficulty
and has an acceptance rate of about 73% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Matrix
- Simulation
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 73: Set Matrix Zeroes
Solved On The Same Day
- problem 257: Binary Tree Paths
- problem 551: Student Attendance Record I
- problem 605: Can Place Flowers
- problem 236: Lowest Common Ancestor of a Binary Tree
- problem 397: Integer Replacement
- problem 413: Arithmetic Slices
- problem 525: Contiguous Array
- problem 567: Permutation in String
Extra
- 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