Leetcode 3127. Make a Square with the Same Color
You are given a matrix grid
of size n x n
filled with integers from 1 to 10 representing different colors. Your task is to determine the minimum number of recoloring operations needed to turn this n x n
grid into an n x n
grid where every element in the grid has the same color.
n
? (1 <= n <= 50
)Given the constraints, let’s proceed to outline the solution.
To determine the minimum recoloring operations:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int minOperationsToOneColor(vector<vector<int>>& grid) {
unordered_map<int, int> colorCount;
int n = grid.size();
// Count the frequency of each color in the grid
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
colorCount[grid[i][j]]++;
}
}
// Find the color with the maximum frequency
int maxColorFrequency = 0;
for (const auto& entry : colorCount) {
if (entry.second > maxColorFrequency) {
maxColorFrequency = entry.second;
}
}
// The minimum number of operations needed is to convert
// all other cells to the color with the highest frequency.
return n * n - maxColorFrequency;
}
int main() {
vector<vector<int>> grid = {
{1, 2, 1},
{1, 3, 2},
{3, 2, 1}
};
cout << "Minimum operations to make the grid one color: "
<< minOperationsToOneColor(grid) << endl;
return 0;
}
n x n
grid.This approach ensures that we efficiently determine the minimum number of recoloring operations required to make the grid uniform in color.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?