2018-10-25 leetcode Game of Life Game of Lifeanother solution - 36ms 1234567891011121314151617181920212223242526272829class Solution: def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ if not board or not board[0]: return m, n = len(board), len(board[0]) for i, row in enumerate(board): for j, ele in enumerate(row): count = 0 for a in range(max(0, i - 1), min(i + 2, m)): for b in range(max(0, j - 1), min(j + 2, n)): # skip i, j itself, (a, b) is (i, j)'s eight neighbors # should count current_alive(1) and formerly_alive(2) if (a, b) != (i, j) and 1 <= board[a][b] <= 2: count += 1 if board[i][j] == 0: if count == 3: board[i][j] = 3 else: if count < 2 or count > 3: board[i][j] = 2 for i in range(m): for j in range(n): if board[i][j] == 2: board[i][j] = 0 elif board[i][j] == 3: board[i][j] = 1 test code 123456In [16]: in_arr = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]In [17]: s = Solution(); s.gameOfLife(in_arr)In [18]: in_arrOut[18]: [[0, 0, 0], [1, 0, 1], [0, 1, 1], [0, 1, 0]] leet code 康威生命游戏 Newer Sort Colors Older Insert Delete GetRandom O(1)