File tree Expand file tree Collapse file tree 1 file changed +97
-0
lines changed
Expand file tree Collapse file tree 1 file changed +97
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ void flip_col(int col , vector<vector<int>> &grid , int n)
4+ {
5+ for(int row = 0 ; row < n ; row++)
6+ {
7+ if(grid[row][col] == 0)
8+ {
9+ grid[row][col] = 1;
10+ }
11+ else
12+ {
13+ grid[row][col] = 0;
14+ }
15+ }
16+ }
17+ void flip_row(int row , vector<vector<int>> &grid , int m)
18+ {
19+ for(int col = 0 ; col < m ; col++)
20+ {
21+ if(grid[row][col] == 0)
22+ {
23+ grid[row][col] = 1;
24+ }
25+ else
26+ {
27+ grid[row][col] = 0;
28+ }
29+ }
30+ }
31+
32+ int value(vector<int> &temp)
33+ {
34+ int n = temp.size();
35+ int val = 1;
36+ int ans = 0;
37+
38+ for(int i = n-1 ; i >= 0 ; i--)
39+ {
40+ int bit = temp[i];
41+
42+ ans += (bit * val);
43+
44+ val = (val << 1);
45+ }
46+
47+ return ans;
48+ }
49+
50+ int matrixScore(vector<vector<int>>& grid) {
51+ int n = grid.size();
52+ int m = grid[0].size();
53+
54+ // First focus on each row -> if starting element is 0 => Flip whole row.
55+ for(int row = 0 ; row < n ; row++)
56+ {
57+ if(grid[row][0] == 0)
58+ {
59+ flip_row(row , grid , m);
60+ }
61+ }
62+
63+ // focus on each column -> if number of zeros > number of 1 => Flip Whole column.
64+ for(int col = 0 ; col < m ; col++)
65+ {
66+ int zeros = 0 , ones = 0;
67+
68+ for(int row = 0 ; row < n ; row++)
69+ {
70+ if(grid[row][col] == 0)
71+ {
72+ zeros++;
73+ }
74+ else
75+ {
76+ ones++;
77+ }
78+ }
79+
80+ if(zeros > ones)
81+ {
82+ flip_col(col , grid , n);
83+ }
84+ }
85+
86+
87+ // now Find the integer number for each row and add it to answer.
88+ int ans = 0;
89+
90+ for(int i = 0 ; i < n ; i++)
91+ {
92+ ans += value(grid[i]);
93+ }
94+
95+ return ans;
96+ }
97+ };
You can’t perform that action at this time.
0 commit comments