-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path861. Score After Flipping Matrix
97 lines (83 loc) · 2.05 KB
/
861. Score After Flipping Matrix
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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;
}
};