
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 public void GameOfLife(int[][] board) {
int m = board.Length, n = board[0].Length;
int[] directions = {-1, 0, 1};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int liveNeighbors = 0;
foreach (int dx in directions) {
foreach (int dy in directions) {
if (dx == 0 && dy == 0) continue;
int ni = i + dx, nj = j + dy;
if (ni >= 0 && ni < m && nj >= 0 && nj < n && Math.Abs(board[ni][nj]) == 1) {
liveNeighbors++;
}
}
}
if (board[i][j] == 1 && (liveNeighbors < 2 || liveNeighbors > 3))
board[i][j] = 2;
else if (board[i][j] == 0 && liveNeighbors == 3)
board[i][j] = -1;
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == -1) {
board[i][j] = 1;
} else if (board[i][j] == 2) {
board[i][j] = 0;
}
}
}
}
}
C# leans on temporal discrete float values to institute direct state traversal occupations otherwise printed through implicit copying in data arrays, leading to a succinct mechanism collapsing multiple operational cycles.