Program to count number of operations required to all cells into same color in Python

When we have a two-dimensional matrix where each cell contains a value representing its color, we need to find the minimum number of operations to make all cells the same color. Adjacent cells (top, bottom, left, right) with the same color form connected groups, and in each operation, we can change all cells in one group to any color.

The key insight is that we should keep the color group with the most connected components unchanged, and convert all other groups to that color.

Problem Understanding

Given the matrix:

2 2 2 2
1 1 1 1
2 3 2 1

We can identify connected groups of the same color and count how many groups each color has. The optimal strategy is to convert all groups to the color that has the most groups.

Algorithm Approach

We use Depth-First Search (DFS) to identify connected components of each color:

  1. For each unvisited cell, perform DFS to mark all connected cells of the same color
  2. Count the number of connected groups for each color
  3. Keep the color with the most groups unchanged
  4. Return the sum of groups for all other colors

Implementation

from collections import defaultdict

class Solution:
    def solve(self, matrix):
        if not matrix:
            return 0
        
        def dfs(i, j, matrix, val):
            n, m = len(matrix), len(matrix[0])
            if i < 0 or i >= n or j < 0 or j >= m:
                return
            if matrix[i][j] == -1 or matrix[i][j] != val:
                return
            
            matrix[i][j] = -1  # Mark as visited
            dfs(i, j + 1, matrix, val)
            dfs(i + 1, j, matrix, val)
            dfs(i, j - 1, matrix, val)
            dfs(i - 1, j, matrix, val)
        
        n, m = len(matrix), len(matrix[0])
        color_groups = defaultdict(int)
        
        for i in range(n):
            for j in range(m):
                val = matrix[i][j]
                if val != -1:
                    color_groups[val] += 1
                    dfs(i, j, matrix, val)
        
        # Find the color with maximum groups
        max_groups = max(color_groups.values())
        
        # Sum of all groups minus the largest group
        return sum(color_groups.values()) - max_groups

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

print(ob.solve(matrix))
2

How It Works

In the example matrix:

  • Color 1: Has 2 connected groups (one group in row 2, another single cell in bottom-right)
  • Color 2: Has 2 connected groups (top row, and bottom-left single cell)
  • Color 3: Has 1 connected group (single cell)

Since colors 1 and 2 both have the maximum number of groups (2), we keep one of them unchanged and convert the other groups. Total groups = 5, maximum groups = 2, so minimum operations = 5 - 2 = 3.

Key Points

  • DFS marks visited cells with -1 to avoid revisiting
  • Each DFS call counts one connected component
  • The optimal strategy always keeps the color with most groups
  • Time complexity: O(n×m) where n and m are matrix dimensions

Conclusion

This solution uses DFS to count connected components for each color, then applies the greedy strategy of keeping the most frequent color unchanged. The minimum operations equals total groups minus the maximum groups for any single color.

Updated on: 2026-03-25T10:46:02+05:30

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements