-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path05_GameOfLife.py
More file actions
48 lines (42 loc) · 1.62 KB
/
05_GameOfLife.py
File metadata and controls
48 lines (42 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# Question link - https://leetcode.com/problems/game-of-life/description/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
1 - live cell , 0 - dead cell
following the structure of state
original | new state | state
--------- | ---------- | --------
0 | 0 | 0
1 | 0 | 1
0 | 1 | 2
1 | 1 | 3
"""
ROWS , COLS = len(board) , len(board[0])
# helper function
def calcaluteNeighbours(r , c):
nei = 0
for i in range(r-1,r+2):
for j in range(c-1,c+2):
if ((i==r and j==c) or i<0 or j<0 or i==ROWS or j==COLS):
continue
elif board[i][j] in [1,3]:
nei += 1
return nei
for r in range(ROWS):
for c in range(COLS):
# Calculate the neighbours
nei = calcaluteNeighbours(r , c)
if board[r][c]: #live
if nei in [2,3]:
board[r][c] = 3
elif nei == 3:
board[r][c] = 2
# Converting the board for 2 and 3 state
for r in range(ROWS):
for c in range(COLS):
# State is 1 , then 0
if board[r][c] == 1:
board[r][c] = 0
elif board[r][c] in [2,3]:
board[r][c] = 1