Advertisement
jinhuang1102

289. Game of Life

Feb 15th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. class Solution:
  2.     def gameOfLife(self, board: 'List[List[int]]') -> 'None':
  3.         """
  4.        Do not return anything, modify board in-place instead.
  5.        """
  6.         # create the direction vector
  7.         dx = [-1, -1, -1, 0, 0, 1, 1, 1]
  8.         dy = [-1, 0, 1, -1, 1, -1, 0, 1]
  9.        
  10.         for i in range(0, len(board)):              # go through each cell in the board
  11.             for j in range(0, len(board[0])):
  12.                
  13.                 live = 0                            # accumulate the live state cell
  14.                
  15.                 for d in range(0, 8):               # go through surrounding 8 cells
  16.                     x = i + dx[d]
  17.                     y = j + dy[d]
  18.                    
  19.                     if x > -1 and x < len(board) and y > -1 and y < len(board[0]):  # houlding the boundary cases
  20.                         if board[x][y] == 1 or board[x][y] == 2:         # if the surrounding cell is live accumulate the live number
  21.                             live += 1
  22.                
  23.                 if board[i][j] == 1:                # calculate the state of the current cell
  24.                     if live < 2 or live > 3:
  25.                         board[i][j] = 2
  26.  
  27.                 elif board[i][j] == 0:                    
  28.                     if live == 3:
  29.                         board[i][j] = 3
  30.  
  31.                        
  32.         for i in range(0, len(board)):
  33.             for j in range(0, len(board[0])):
  34.                 board[i][j] = board[i][j] % 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement