ogv

Untitled

ogv
Nov 13th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. // Runtime: 0 ms, faster than 100.00% of Java online submissions for Score After Flipping Matrix.
  2. class Solution {
  3.     int[][] a;
  4.     int m;
  5.     int n;
  6.     public int matrixScore(int[][] A) {
  7.         a = A;
  8.         m = a.length;
  9.         n = a[0].length;
  10.                
  11.         for (int r = 0; r < m; r++)
  12.             if (a[r][0] == 0) flipRow(r);
  13.        
  14.         return opt(0);
  15.     }
  16.    
  17.     private int opt(int c){
  18.         if (c == n) return score();
  19.        
  20.         int ones = 0;
  21.         for (int r = 0; r < m; r++)
  22.             if (a[r][c] == 1) ones++;
  23.        
  24.         int max = 0;
  25.         if (ones > m/2){
  26.             max = Math.max(max, opt(c+1));
  27.         }
  28.         else {
  29.             flipColumn(c);
  30.             max = Math.max(max, opt(c+1));
  31.         }
  32.         return max;
  33.     }
  34.    
  35.     private int score() {
  36.         int sum = 0;
  37.        
  38.         for (int r = 0; r < m; r++) {
  39.             int num = 0;
  40.             int p = 1;
  41.             for (int c = n-1; c >= 0; c--){
  42.                 if (a[r][c] == 1) num += p;
  43.                 p <<= 1;
  44.             }
  45.             sum += num;
  46.         }
  47.        
  48.         return sum;
  49.     }
  50.    
  51.     private void flipColumn(int c) {
  52.         for (int r = 0; r < m; r++) a[r][c] = 1 - a[r][c];
  53.     }
  54.    
  55.     private void flipRow(int r) {
  56.         for (int c = 0; c < n; c++) a[r][c] = 1 - a[r][c];
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment