LeetCode 289. Game of Life

November 6, 2024

Final matrix problem, this one a bit special to me. My first repo in Github is for a Game of Life program in C++. I created it in 2011 as a science fair project.

Solution

This method uses constant space by usind integer division and modulo operations. We use this to update state in-place, then we traverse over the grid again to convert the values back to 0 or 1.

1class Solution:
2 def gameOfLife(self, board: List[List[int]]) -> None:
3 """
4 Do not return anything, modify board in-place instead.
5 """
6 neighbors = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
7 for i, row in enumerate(board):
8 for j, cell in enumerate(row):
9 neighborCount = 0
10 for (nx, ny) in neighbors:
11 y, x = i + ny, j + nx
12 if (x >= 0 and y >= 0 and
13 x < len(board[0]) and y < len(board) and
14 board[y][x] % 2):
15 neighborCount += 1
16 if cell % 2 and neighborCount < 2:
17 pass
18 elif cell % 2 and neighborCount == 2 or neighborCount == 3:
19 board[i][j] += 2
20 elif cell % 2 and neighborCount > 3:
21 pass
22 elif not cell % 2 and neighborCount == 3:
23 board[i][j] += 2
24
25 for i in range(len(board)):
26 for j in range(len(board[0])):
27 board[i][j] = board[i][j] // 2
28``
29(n) = m * n

LeetCode 48. Rotate Image

LeetCode 49. Group Anagrams