




Sponsored
Sponsored
This approach creates a copy of the original board. It calculates the new state for each cell using the current state from the original board while updating the new state in the copy. Once all cells have been processed, it updates the original board with the calculated states from the copy.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns, because each cell is visited once.
Space Complexity: O(m * n), due to the additional copy of the board.
1class Solution {
2    public void gameOfLife(int[][] board) {
3        int m = board.length, n = board[0].length;
4        int[][] copy = new int[m][n];
5
6        for (int i = 0; i < m; i++) {
7            for (int j = 0; j < n; j++) {
8                copy[i][j] = board[i][j];
9            }
10        }
11
12        int[] directions = {-1, 0, 1};
13
14        for (int i = 0; i < m; i++) {
15            for (int j = 0; j < n; j++) {
16                int liveNeighbors = 0;
17                for (int dx : directions) {
18                    for (int dy : directions) {
19                        if (dx == 0 && dy == 0) continue;
20                        int ni = i + dx, nj = j + dy;
21                        if (ni >= 0 && ni < m && nj >= 0 && nj < n && copy[ni][nj] == 1) {
22                            liveNeighbors++;
23                        }
24                    }
25                }
26
27                if (copy[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) {
28                    board[i][j] = 0;
29                } else if (copy[i][j] == 0 && liveNeighbors == 3) {
30                    board[i][j] = 1;
31                }
32            }
33        }
34    }
35}
36The Java implementation creates a separate 2D array to keep track of the current state of each cell. The nested loop iterates through all cells, and each cell's live neighbors are counted by checking all eight possible adjacent cells. The new state of each cell is determined by the Game of Life rules and the board is updated accordingly.
This approach uses in-place updates by leveraging different state values. We introduce temporary states: 2 represents a cell that was originally live (1) but will be dead in the next state, and -1 represents a cell that was dead (0) but will be live in the next state. At the end, these temporary states are converted to the final states.
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns.
Space Complexity: O(1), as no additional space is used beyond input storage.
1
The C solution uses the board itself to track changes by representing transitional states so the board can be accurately updated in one iteration by determining the final state in a second pass.