imashutosh51

Game of Life

Oct 16th, 2022 (edited)
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.22 KB | None | 0 0
  1. '''
  2. Logic: We are counting the neighbours of every element,
  3. if the current element is 1 then replacing that 1 with count of neighbours
  4. if the current element is 0 then replacing that 0 with negative of count of neighbours.
  5. after doing above step,we are traversing the matrix again and replacing values as per the condition like
  6. -3 means having 3 neighbours of 0:- change to 1
  7. 2 or 3 means having 2 or 3 neighbours of 1 :-change to 1
  8. rest all conditions 0 so change other values to 0
  9.  
  10. There is one catch,If board[i][j]=1 and 0 neighbours so it will make it 0 so we will make it 1,
  11. anyway it is going to die only but for not disturbing the counting of others,we will make it 1
  12. as it is 1.
  13. '''
  14.  
  15. class Solution:
  16.  
  17.     def count_neighbors(self,i,j,board):
  18.         x = [-1, -1, -1,  0, 0,  1, 1, 1]
  19.         y = [-1,  0,  1, -1, 1, -1, 0, 1]
  20.         row=len(board)
  21.         col=len(board[0])
  22.         ans=0
  23.  
  24.         for k in range(8):
  25.             new_i=i+x[k]
  26.             new_j=j+y[k]
  27.             if new_i>=0 and new_j>=0 and new_i<row and new_j<col and board[new_i][new_j]>0:
  28.                 ans+=1
  29.         return ans
  30.  
  31.     def gameOfLife(self, board: List[List[int]]) -> None:
  32.         #neighbours=8
  33.         #live cell -> <2  or >3 live neighbours-> dies
  34.         #live cell -> 2 or 3 live neighbours-> live
  35.         #dead cell -> =3 live neighbours ->live
  36.         #rules:
  37.             # 1.If it is alive now then it must be positive so if now alive to dead, sign=2
  38.             # 2.if it is dead now then it became alive,sign will be negative, sign=-1
  39.             #this way only 1 or -1 will be alive in the updates board
  40.  
  41.         row=len(board)
  42.         col=len(board[0])
  43.         for i in range(row):
  44.             for j in range(col):
  45.                 n=self.count_neighbors(i,j,board)
  46.                 if board[i][j]==1 and (n<2 or n>3):
  47.                     board[i][j]=2 #-2 means earlier it was alive but now it dies
  48.                 if board[i][j]==0 and n==3:
  49.                     board[i][j]=-1
  50.        
  51.         for i in range(row):
  52.             for j in range(col):
  53.                 if abs(board[i][j])==1:
  54.                     board[i][j]=1
  55.                 else:
  56.                     board[i][j]=0
  57.  
  58.  
  59.                
  60.        
Advertisement
Add Comment
Please, Sign In to add comment