




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.
1def gameOfLife(board):
2    m, n = len(board), len(board[0])
3    copy = [[board[i][j] for j in range(n)] for i in range(m)]
4    directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
5
6    for i in range(m):
7        for j in range(n):
8            live_neighbors = 0
9            for di, dj in directions:
10                ni, nj = i + di, j + dj
11                if 0 <= ni < m and 0 <= nj < n and copy[ni][nj] == 1:
12                    live_neighbors += 1
13
14            if copy[i][j] == 1 and (live_neighbors < 2 or live_neighbors > 3):
15                board[i][j] = 0
16            elif copy[i][j] == 0 and live_neighbors == 3:
17                board[i][j] = 1
18This Python solution copies the board to a new list called 'copy' using list comprehensions. It then iterates through each cell and counts its live neighbors. The Game of Life rules are applied to determine the new state for each cell, which is reflected in the original board.
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.