Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Logic: We are counting the neighbours of every element,
- if the current element is 1 then replacing that 1 with count of neighbours
- if the current element is 0 then replacing that 0 with negative of count of neighbours.
- after doing above step,we are traversing the matrix again and replacing values as per the condition like
- -3 means having 3 neighbours of 0:- change to 1
- 2 or 3 means having 2 or 3 neighbours of 1 :-change to 1
- rest all conditions 0 so change other values to 0
- There is one catch,If board[i][j]=1 and 0 neighbours so it will make it 0 so we will make it 1,
- anyway it is going to die only but for not disturbing the counting of others,we will make it 1
- as it is 1.
- '''
- class Solution:
- def count_neighbors(self,i,j,board):
- x = [-1, -1, -1, 0, 0, 1, 1, 1]
- y = [-1, 0, 1, -1, 1, -1, 0, 1]
- row=len(board)
- col=len(board[0])
- ans=0
- for k in range(8):
- new_i=i+x[k]
- new_j=j+y[k]
- if new_i>=0 and new_j>=0 and new_i<row and new_j<col and board[new_i][new_j]>0:
- ans+=1
- return ans
- def gameOfLife(self, board: List[List[int]]) -> None:
- #neighbours=8
- #live cell -> <2 or >3 live neighbours-> dies
- #live cell -> 2 or 3 live neighbours-> live
- #dead cell -> =3 live neighbours ->live
- #rules:
- # 1.If it is alive now then it must be positive so if now alive to dead, sign=2
- # 2.if it is dead now then it became alive,sign will be negative, sign=-1
- #this way only 1 or -1 will be alive in the updates board
- row=len(board)
- col=len(board[0])
- for i in range(row):
- for j in range(col):
- n=self.count_neighbors(i,j,board)
- if board[i][j]==1 and (n<2 or n>3):
- board[i][j]=2 #-2 means earlier it was alive but now it dies
- if board[i][j]==0 and n==3:
- board[i][j]=-1
- for i in range(row):
- for j in range(col):
- if abs(board[i][j])==1:
- board[i][j]=1
- else:
- board[i][j]=0
Advertisement
Add Comment
Please, Sign In to add comment