Skip to content

Commit 5b84551

Browse files
committed
Merge branch 'master' of https://github.com/CharryWu/leetcode
2 parents 05f3d11 + 7dbfbdf commit 5b84551

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

simulation/289. Game of Life.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def gameOfLife(self, board: List[List[int]]) -> None:
3+
"""
4+
Use 4 values, instead of 2 (0/1), to designate the state after update. This allows us to retain the prev state information so updates of current cell won't affect neighbor cell calculations
5+
1: live -> live cell (no change)
6+
-1: live -> dead cell
7+
check abs(nei) == 1: whether nei cell is previously alive (so update doesn't affect calculating its neighbors' next state)
8+
0: dead -> dead cell (no change)
9+
2: dead -> live cell (doens't affect the abs(nei) check)
10+
11+
After ALL cells have been updated, check if cell is > 0. if > 0, the values are 1, 2, then the post-update cell is alive, otherwise the values are 0, -1, dead
12+
"""
13+
directions = [(1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1), (0,1), (1,1)]
14+
m, n = len(board), len(board[0])
15+
16+
for x in range(m):
17+
for y in range(n):
18+
live = 0
19+
for dx, dy in directions: # count live neighbors
20+
nx, ny = x+dx, y+dy
21+
if 0 <= nx < m and 0 <= ny < n and abs(board[nx][ny]) == 1:
22+
live += 1
23+
if board[x][y] == 1 and (live < 2 or live > 3): # Rule 1 or Rule 3: live -> dead
24+
board[x][y] = -1
25+
if board[x][y] == 0 and live == 3: # Rule 4: dead -> live
26+
board[x][y] = 2
27+
# else: Rule 2 no change: dead -> dead, live -> live
28+
29+
for x in range(m):
30+
for y in range(n):
31+
board[x][y] = 1 if board[x][y] > 0 else 0
32+
return board

0 commit comments

Comments
 (0)