Game of Life
LeetCode 289 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
In-place state encoding: −1 (dies) and 2 (born).
मैंने Game of Life (LeetCode 289) ऐसे हल किया — Matrix पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Every cell must update from the old board, so you can't overwrite values as you go. Encode transitions in place: −1 means 'was alive, now dead', 2 means 'was dead, now alive'. Counting neighbours with abs(value) == 1 still sees the old state.
Approach
- 1
Count live neighbours using abs(cell) == 1.
- 2
A live cell with < 2 or > 3 neighbours becomes −1.
- 3
A dead cell with exactly 3 neighbours becomes 2.
- 4
Final pass: positive → 1, negative → 0.
मैंने कैसे हल किया
In-place state encodingPythonO(m·n) time · O(1) space
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
#live_neighbours<2 - dies
#live_neighbours>3 - dies
#live_neighbours==3
m = len(board)
n = len(board[0])
arr_copy=board.copy()
for i in range(m):
for j in range(n):
live_neighbours=0
for di in range(-1,2):
for dj in range(-1,2):
if not (di == 0 and dj == 0):
nrow = i+di
ncol = j+dj
if 0<=nrow<m and 0<=ncol<n and abs(board[nrow][ncol])==1:
live_neighbours+=1
if (live_neighbours<2 or live_neighbours>3) and board[i][j]==1:
board[i][j]=-1
if live_neighbours==3 and board[i][j]==0:
board[i][j]=2
for i in range(m):
for j in range(n):
if board[i][j]>0:
board[i][j]=1
elif board[i][j]<0:
board[i][j]=0
Game of Life — अक्सर पूछे जाने वाले प्रश्न
Game of Life के पीछे intuition क्या है?
Every cell must update from the old board, so you can't overwrite values as you go. Encode transitions in place: −1 means 'was alive, now dead', 2 means 'was dead, now alive'. Counting neighbours with abs(value) == 1 still sees the old state.
Game of Life (LeetCode 289) कैसे हल करें?
1. Count live neighbours using abs(cell) == 1. 2. A live cell with < 2 or > 3 neighbours becomes −1. 3. A dead cell with exactly 3 neighbours becomes 2. 4. Final pass: positive → 1, negative → 0.
Game of Life की time और space complexity क्या है?
Time: O(m·n)। Space: O(1)। (Accepted approach: In-place state encoding।)
Game of Life में आम गलतियाँ क्या हैं?
board.copy() is shallow — it doesn't protect the rows; the encoding is what makes it correct.