# 289-game-of-life Try it on leetcode ## Description

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):

  1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population.
  4. 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:

 

Follow up:

## Solution(Python) ```Python class Solution: # def gameOfLife(self, board: List[List[int]]) -> None: # """ # Do not return anything, modify board in-place instead. # """ # if board is None or len(board) == 0: # return # m = len(board) # n = len(board[0]) # for i in range(m): # for j in range(n): # lives = self.count_live_neighours(i,j,m,n,board) # if board[i][j] == 1 and lives >= 2 and lives <= 3: # board[i][j] = 3 # if board[i][j] == 0 and lives == 3: # board[i][j] = 2 # for i in range(m): # for j in range(n): # board[i][j] >>= 1 # def count_live_neighours(self,i,j,m,n,board): # lives = 0 # for x in range(max(i-1,0),min(i+1,m-1)+1): # for y in range(max(j-1,0),min(j+1,n-1)+1): # lives+=board[x][y]&1 # lives -= board[i][j]&1 # return lives def gameOfLifeInfinite(self, live): ctr = collections.Counter( (I, J) for i, j in live for I in range(i - 1, i + 2) for J in range(j - 1, j + 2) if I != i or J != j ) return {ij for ij in ctr if ctr[ij] == 3 or ctr[ij] == 2 and ij in live} def gameOfLife(self, board): live = { (i, j) for i, row in enumerate(board) for j, live in enumerate(row) if live } live = self.gameOfLifeInfinite(live) for i, row in enumerate(board): for j in range(len(row)): row[j] = int((i, j) in live) ```