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

This problem implements Conway's Game of Life, where we need to find the next state of a 2D binary matrix. A cell's neighbors are its immediate horizontal, vertical and diagonal cells (8 neighbors total). The rules are:

  • Any living cell with two or three living neighbors survives

  • Any dead cell with exactly three living neighbors becomes alive

  • All other cells die or remain dead

Example Input and Output

Given this input matrix −

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

The output will be −

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

Algorithm

The approach is −

  • Create a result matrix of same dimensions filled with zeros

  • For each cell, count its living neighbors in all 8 directions

  • Apply the Game of Life rules based on current state and neighbor count

  • Return the updated matrix

Implementation

class Solution:
    def solve(self, matrix):
        n, m = len(matrix), len(matrix[0])
        res = [[0 for j in range(m)] for i in range(n)]
        
        for i in range(n):
            for j in range(m):
                s = 0
                
                # Count living neighbors in all 8 directions
                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]
                
                # Subtract current cell from neighbor count
                s -= matrix[i][j]
                
                # Apply Game of Life rules
                if matrix[i][j] == 1:  # Living cell
                    if s == 2 or s == 3:
                        res[i][j] = 1
                else:  # Dead cell
                    if s == 3:
                        res[i][j] = 1
                        
        return res

# Test the solution
ob = Solution()
matrix = [
    [1, 1, 0, 0],
    [0, 1, 0, 0],
    [0, 1, 0, 1],
    [1, 1, 0, 1]
]

result = ob.solve(matrix)
print("Input matrix:")
for row in matrix:
    print(row)

print("\nOutput matrix:")
for row in result:
    print(row)
Input matrix:
[1, 1, 0, 0]
[0, 1, 0, 0]
[0, 1, 0, 1]
[1, 1, 0, 1]

Output matrix:
[1, 1, 0, 0]
[0, 1, 0, 0]
[0, 1, 0, 0]
[1, 1, 0, 0]

How It Works

Let's trace through cell [2][3] which changes from 1 to 0 −

  • Current value: 1 (living cell)

  • Neighbors: [1][2]=0, [1][3]=0, [2][2]=0, [3][2]=0, [3][3]=1

  • Living neighbor count: 1

  • Since living cell has only 1 neighbor (less than 2), it dies

Conclusion

This solution implements Conway's Game of Life by counting each cell's living neighbors and applying the survival rules. The algorithm has O(n×m) time complexity where n and m are matrix dimensions.

Updated on: 2026-03-25T12:12:45+05:30

238 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements