[leetcode]Game of Life

python3

要原地变换,就要利用int的位数。这里用了第二位,就是%2以及+2的做法,不改变奇偶性。

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        # m * n
        m = len(board)
        if m == 0:
            return
        n = len(board[0])
        if n == 0:
            return
        for i in range(m):
            for j in range(n):
                # check neighbors
                liveCount = 0
                for dx in [-1, 0, 1]:
                    for dy in [-1, 0, 1]:
                        if dx == 0 and dy == 0:
                            continue
                        x = i + dx
                        y = j + dy
                        if x < 0 or x >= m or y < 0 or y >= n:
                            continue
                        if board[x][y] % 2 == 1:
                            liveCount += 1
                if board[i][j] % 2 == 0 and liveCount == 3:
                    board[i][j] += 2
                elif board[i][j] % 2 == 1 and liveCount < 2:
                    board[i][j] += 0
                elif board[i][j] % 2 == 1 and liveCount in [2, 3]:
                    board[i][j] += 2
                elif board[i][j] % 2 == 1 and liveCount >= 3:
                    board[i][j] += 0
                else:
                    board[i][j] += (board[i][j] % 2) * 2
            
        for i in range(m):
            for j in range(n):
                board[i][j] = board[i][j] // 2 % 2

  

上一篇:第7关:小游戏大学问(2)


下一篇:The First Blog