Skip to content

Create 861. Score After Flipping Matrix #477

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions 861. Score After Flipping Matrix
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
class Solution {
public:
void flip_col(int col , vector<vector<int>> &grid , int n)
{
for(int row = 0 ; row < n ; row++)
{
if(grid[row][col] == 0)
{
grid[row][col] = 1;
}
else
{
grid[row][col] = 0;
}
}
}
void flip_row(int row , vector<vector<int>> &grid , int m)
{
for(int col = 0 ; col < m ; col++)
{
if(grid[row][col] == 0)
{
grid[row][col] = 1;
}
else
{
grid[row][col] = 0;
}
}
}

int value(vector<int> &temp)
{
int n = temp.size();
int val = 1;
int ans = 0;

for(int i = n-1 ; i >= 0 ; i--)
{
int bit = temp[i];

ans += (bit * val);

val = (val << 1);
}

return ans;
}

int matrixScore(vector<vector<int>>& grid) {
int n = grid.size();
int m = grid[0].size();

// First focus on each row -> if starting element is 0 => Flip whole row.
for(int row = 0 ; row < n ; row++)
{
if(grid[row][0] == 0)
{
flip_row(row , grid , m);
}
}

// focus on each column -> if number of zeros > number of 1 => Flip Whole column.
for(int col = 0 ; col < m ; col++)
{
int zeros = 0 , ones = 0;

for(int row = 0 ; row < n ; row++)
{
if(grid[row][col] == 0)
{
zeros++;
}
else
{
ones++;
}
}

if(zeros > ones)
{
flip_col(col , grid , n);
}
}


// now Find the integer number for each row and add it to answer.
int ans = 0;

for(int i = 0 ; i < n ; i++)
{
ans += value(grid[i]);
}

return ans;
}
};
Loading