Skip to content

Instantly share code, notes, and snippets.

@amankharwal
Created December 25, 2020 11:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amankharwal/e04369de79c4060fb7edab5c29ea22b7 to your computer and use it in GitHub Desktop.
Save amankharwal/e04369de79c4060fb7edab5c29ea22b7 to your computer and use it in GitHub Desktop.
class game_of_life:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# Neighbors array to find 8 neighboring cells for a given cell
neighbors = [(1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1), (0,1), (1,1)]
rows = len(board)
cols = len(board[0])
# Create a copy of the original board
copy_board = [[board[row][col] for col in range(cols)] for row in range(rows)]
# Iterate through board cell by cell.
for row in range(rows):
for col in range(cols):
# For each cell count the number of live neighbors.
live_neighbors = 0
for neighbor in neighbors:
r = (row + neighbor[0])
c = (col + neighbor[1])
# Check the validity of the neighboring cell and if it was originally a live cell.
# The evaluation is done against the copy, since that is never updated.
if (r < rows and r >= 0) and (c < cols and c >= 0) and (copy_board[r][c] == 1):
live_neighbors += 1
# Rule 1 or Rule 3
if copy_board[row][col] == 1 and (live_neighbors < 2 or live_neighbors > 3):
board[row][col] = 0
# Rule 4
if copy_board[row][col] == 0 and live_neighbors == 3:
board[row][col] = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment