zoukankan      html  css  js  c++  java
  • [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
    

      

  • 相关阅读:
    Service、chkconfig命令
    mongoDB 入门
    HTTP 缓存
    MIME类型记录
    CSS3 动画 思维导图
    部署Seafile服务
    AngularJS 学习笔记
    Bootstrap3 学习笔记
    CSS 弹性盒
    传送门(portal)
  • 原文地址:https://www.cnblogs.com/lautsie/p/12245826.html
Copyright © 2011-2022 走看看