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.
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 = 010 for (nx, ny) in neighbors:11 y, x = i + ny, j + nx12 if (x >= 0 and y >= 0 and13 x < len(board[0]) and y < len(board) and14 board[y][x] % 2):15 neighborCount += 116 if cell % 2 and neighborCount < 2:17 pass18 elif cell % 2 and neighborCount == 2 or neighborCount == 3:19 board[i][j] += 220 elif cell % 2 and neighborCount > 3:21 pass22 elif not cell % 2 and neighborCount == 3:23 board[i][j] += 22425 for i in range(len(board)):26 for j in range(len(board[0])):27 board[i][j] = board[i][j] // 228``29(n) = m * n
LeetCode 48. Rotate Image
LeetCode 49. Group Anagrams