[Leetcode Series] [algorithm] [medium] Game of Life

topic:

Topic links:  https://leetcode-cn.com/problems/game-of-life/

 

Problem-solving ideas:

Method a: use of extra space to store the original array, this array without any additional changes to the determination of the squared data

Method Two: Adding additional state to determine the state before modification, additional update cycle state

  1. 0: dead
  2. 1: Health
  3. 2: Dead => Health
  4. 3: Health => dead

 

Code:

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        """
        0 : dead
        1 : live
        2 : dead -> live
        3 : live -> dead
        """
        live_state = [1, 3]
        dead_state = [0, 2]
        def get_state(i, j, board):
            ret = 0
            if i >= 0 and i < len(board) and j >= 0 and j < len(board[0]):
                if board[i][j] in live_state:
                    ret = 1
                else:
                    ret = 0

            return ret

        def get_live_num(i, j, board):
            live_num = 0
            # upper left
            live_num += get_state(i - 1, j - 1, board)

            # upper
            live_num += get_state(i - 1, j, board)
            
            # upper right
            live_num += get_state(i - 1, j + 1, board)
            
            # left
            live_num += get_state(i, j - 1, board)
            
            # right
            live_num += get_state(i, j + 1, board)
            
            # lower left
            live_num += get_state(i + 1, j - 1, board)
            
            # lower
            live_num += get_state(i + 1, j, board)
            
            # lower right
            live_num += get_state(i + 1, j + 1, board)
            return live_num


        for i in range(0, len(board)):
            for j in range(0, len(board[0])):
                live_num = get_live_num(i, j, board)
                if 0 == board[i][j] and 3 == live_num:
                    board[i][j] = 2
                elif 1 == board[i][j] and (live_num < 2 or live_num > 3):
                    board[i][j] = 3
                    
        for i in range(0, len(board)):
            for j in range(0, len(board[0])):
                if board[i][j] == 2:
                    board[i][j] = 1
                elif board[i][j] == 3:
                    board[i][j] = 0

 

Published 100 original articles · won praise 4 · Views 1476

Guess you like

Origin blog.csdn.net/songyuwen0808/article/details/105283310