




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.
1public class Solution {
2    public void GameOfLife(int[][] board) {
3        int m = board.Length, n = board[0].Length;
4        int[][] copy = new int[m][];
5        for (int i = 0; i < m; i++) {
6            copy[i] = new int[n];
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        for (int i = 0; i < m; i++) {
14            for (int j = 0; j < n; j++) {
15                int liveNeighbors = 0;
16                foreach (int dx in directions) {
17                    foreach (int dy in directions) {
18                        if (dx == 0 && dy == 0) continue;
19                        int ni = i + dx, nj = j + dy;
20                        if (ni >= 0 && ni < m && nj >= 0 && nj < n && copy[ni][nj] == 1) {
21                            liveNeighbors++;
22                        }
23                    }
24                }
25
26                if (copy[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3))
27                    board[i][j] = 0;
28                else if (copy[i][j] == 0 && liveNeighbors == 3)
29                    board[i][j] = 1;
30            }
31        }
32    }
33}
34This C# implementation utilizes an extra jagged array to store a copy of the current state of the board. The solution iterates through each cell and determines the live neighbors by checking all eight possible directions. The Game of Life rules are applied to update the board in-place once all cells have been processed.
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.