Suppose we have a two-dimensional matrix M. Now in each cell contains a value that represents its color, and adjacent cells (top, bottom, left, right) with the same color are to be grouped together. Now, consider an operation where we set all cells in one group to some color. Then finally find the minimum number of operations required so that every cell has the same color. And when the color is transformed, it cannot be set again.
So, if the input is like
2 | 2 | 2 | 2 |
1 | 1 | 1 | 1 |
2 | 3 | 2 | 1 |
Then the output will be 2, as We can fill the group with 2 as color into 1 and then fill 3 with 1.
To solve this, we will follow these steps−
if matrix is empty, then
return 0
Define a function dfs() . This will take i, j, matrix, val
n := row count of matrix, m := col count of matrix
if i < 0 or i > n - 1 or j < 0 or j > m - 1, then
return
if matrix[i, j] is same as -1, then
return
if matrix[i, j] is same as val, then
matrix[i, j] := -1
dfs(i, j + 1, matrix, val)
dfs(i + 1, j, matrix, val)
dfs(i, j - 1, matrix, val)
dfs(i - 1, j, matrix, val)
otherwise,
return
From the main method, do the following−
n := row count of matrix, m := col count of matrix
d := empty map
for i in range 0 to n-1, do
for j in range 0 to m-1, do
val := matrix[i, j]
if val is not same as -1, then
d[val] := d[val] + 1
dfs(i, j, matrix, val)
sort dictionary elements of f based on their values
safe := last element of l
res := 0
for each key value pairs k and v of d, do
if k is not same as safe, then
res := res + v
return res
Let us see the following implementation to get better understanding −
Example
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 - 1 or j < 0 or j > m - 1: return if matrix[i][j] == -1: return if matrix[i][j] == val: matrix[i][j] = -1 dfs(i, j + 1, matrix, val) dfs(i + 1, j, matrix, val) dfs(i, j - 1, matrix, val) dfs(i - 1, j, matrix, val) else: return n, m = len(matrix), len(matrix[0]) d = defaultdict(int) for i in range(n): for j in range(m): val = matrix[i][j] if val != -1: d[val] += 1 dfs(i, j, matrix, val) l = sorted(d,key=lambda x: d[x]) safe = l[-1] res = 0 for k, v in d.items(): if k != safe: res += v return res ob = Solution() matrix = [ [2, 2, 2, 2], [1, 1, 1, 1], [2, 3, 2, 1] ] print(ob.solve(matrix))
Input
matrix = [[2, 2, 2, 2],[1, 1, 1, 1],[2, 3, 2, 1]]
Output
2