# Program to find next state of next cell matrix state in Python?

PythonServer Side ProgrammingProgramming

Suppose we have a 2D binary matrix where a 1 means a live cell and a 0 means a dead cell. A cell's neighbors are its immediate horizontal, vertical and diagonal cells. We have to find the next state of the matrix using these rules

• Any living cell with two or three living neighbors lives.

• Any dead cell with three living neighbors becomes a live cell.

• All other cells die.

So, if the input is like

 1 1 0 0 0 1 0 0 0 1 0 1 1 1 0 1

then the output will be

 1 1 0 0 0 1 0 0 0 1 0 0 1 1 0 0

To solve this, we will follow these steps:

• n := row size of matrix, m := column size of matrix

• res := a matrix of size n x m, and fill with 0

• for i in range 0 to n, do

• for j in range 0 to m, do

• s := 0

• if matrix[i, j] is same as 0, then

• for k in range i - 1 to i + 1, do

• or h in range j - 1 to j + 1, do

• if 0 <= k < n and 0 <= h < m, then

• s := s + matrix[k, h]

• res[i, j] := [0, 1, true when s is same as 3]

• otherwise,

• for k in range i - 1 to i + 1, do

• for h in range j - 1 to j + 1, do

• if 0 <= k < n and 0 <= h < m, then

• s := s + matrix[k, h]

• if s is either 3 or 4, then

• res[i, j] := 1

• return res

Let us see the following implementation to get better understanding:

## Example

Live Demo

class Solution:
def solve(self, matrix):
n, m = len(matrix), len(matrix)
res = [[0 for j in range(m)] for i in range(n)]
for i in range(n):
for j in range(m):
s = 0
if matrix[i][j] == 0:
for k in range(i - 1, i + 2):
for h in range(j - 1, j + 2):
if 0 <= k < n and 0 <= h < m:
s += matrix[k][h]
res[i][j] = [0, 1][s == 3]
else:
for k in range(i - 1, i + 2):
for h in range(j - 1, j + 2):
if 0 <= k < n and 0 <= h < m:
s += matrix[k][h]
if s in [3, 4]:
res[i][j] = 1
return res

ob = Solution()
matrix = [
[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 1],
[1, 1, 0, 1]
]

print(ob.solve(matrix))

## Input

[[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 1],
[1, 1, 0, 1] ]

## Output

[[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[1, 1, 0, 0]]