-
Notifications
You must be signed in to change notification settings - Fork 43
/
game-of-life.py
277 lines (226 loc) · 10.7 KB
/
game-of-life.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""
289. Game of Life
Medium
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
The board is made up of an m x n grid of cells, where each cell has an initial state: live (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):
Any live cell with fewer than two live neighbors dies as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population.
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the m x n grid board, return the next state.
Example 1:
Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
Example 2:
Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 25
board[i][j] is 0 or 1.
Follow up:
Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.
In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
"""
# V0
class Solution:
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
# V1
# https://leetcode.com/problems/game-of-life/solution/
#Time Complexity: O(M×N), where MM is the number of rows and NN is the number of columns of the Board.
#Space Complexity: O(M×N), MM is the number of rows and NN is the number of columns of the Board. This is the space occupied by the copy board we created initially.
class Solution:
def gameOfLife(self, board):
"""
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
# for testing
return board
### Test case
s=Solution()
assert s.gameOfLife([[0,0,0,0,0,0],[0,0,1,1,0,0],[0,1,0,0,1,0],[0,0,1,1,0,0],[0,0,0,0,0,0]]) == [[0,0,0,0,0,0],[0,0,1,1,0,0],[0,1,0,0,1,0],[0,0,1,1,0,0],[0,0,0,0,0,0]]
assert s.gameOfLife([[]]) == [[]]
assert s.gameOfLife([[1,1,1]]) == [[0,1,0]]
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/82809923
# IDEA : GREEDY
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if board and board[0]:
M, N = len(board), len(board[0])
board_next = copy.deepcopy(board)
for m in range(M):
for n in range(N):
lod = self.liveOrDead(board, m, n)
if lod == 2:
board_next[m][n] = 0
elif lod == 1:
board_next[m][n] = 1
for m in range(M):
for n in range(N):
board[m][n] = board_next[m][n]
def liveOrDead(self, board, i, j):# return 0-nothing,1-live,2-dead
ds = [(1, 1), (1, -1), (1, 0), (-1, 1), (-1, 0), (-1, -1), (0, 1), (0, -1)]
live_count = 0
M, N = len(board), len(board[0])
for d in ds:
r, c = i + d[0], j + d[1]
if 0 <= r < M and 0 <= c < N:
if board[r][c] == 1:
live_count += 1
if live_count < 2 or live_count > 3:
return 2
elif board[i][j] == 1 or (live_count == 3 and board[i][j] ==0):
return 1
else:
return 0
# V1''
# https://leetcode.com/problems/game-of-life/solution/
#Time Complexity: O(M×N), where MM is the number of rows and NN is the number of columns of the Board.
#Space Complexity: O(1)
class Solution:
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])
# 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:
# row and column of the neighboring cell
r = (row + neighbor[0])
c = (col + neighbor[1])
# Check the validity of the neighboring cell and if it was originally a live cell.
if (r < rows and r >= 0) and (c < cols and c >= 0) and abs(board[r][c]) == 1:
live_neighbors += 1
# Rule 1 or Rule 3
if board[row][col] == 1 and (live_neighbors < 2 or live_neighbors > 3):
# -1 signifies the cell is now dead but originally was live.
board[row][col] = -1
# Rule 4
if board[row][col] == 0 and live_neighbors == 3:
# 2 signifies the cell is now live but was originally dead.
board[row][col] = 2
# Get the final representation for the newly updated board.
for row in range(rows):
for col in range(cols):
if board[row][col] > 0:
board[row][col] = 1
else:
board[row][col] = 0
# V1'''
# http://bookshadow.com/weblog/2015/10/04/leetcode-game-life/
# IDEA : BIT MANIPULATION
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
dx = (1, 1, 1, 0, 0, -1, -1, -1)
dy = (1, 0, -1, 1, -1, 1, 0, -1)
for x in range(len(board)):
for y in range(len(board[0])):
lives = 0
for z in range(8):
nx, ny = x + dx[z], y + dy[z]
lives += self.getCellStatus(board, nx, ny)
if lives + board[x][y] == 3 or lives == 3:
board[x][y] |= 2
for x in range(len(board)):
for y in range(len(board[0])):
board[x][y] >>= 1
def getCellStatus(self, board, x, y):
if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]):
return 0
return board[x][y] & 1
# V2
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0]) if m else 0
for i in range(m):
for j in range(n):
count = 0
## Count live cells in 3x3 block.
for I in range(max(i-1, 0), min(i+2, m)):
for J in range(max(j-1, 0), min(j+2, n)):
count += board[I][J] & 1
# if (count == 4 && board[i][j]) means:
# Any live cell with three live neighbors lives.
# if (count == 3) means:
# Any live cell with two live neighbors.
# Any dead cell with exactly three live neighbors lives.
if (count == 4 and board[i][j]) or count == 3:
board[i][j] |= 2 # Mark as live.
for i in range(m):
for j in range(n):
board[i][j] >>= 1 # Update to the next state.