2128. Remove All Ones With Row and Column Flips

in row flips or col flips

want all zeros, only happen in only has two patterns in a matrix

normal or reverse pattern, just 2 patterns

T: O(mn)
S: O(1)
class Solution {
    public boolean removeOnes(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        if (grid.length == 1) {
            return true;
        }
        
        // get first row's string, and reverse string
        StringBuilder first = new StringBuilder();
        StringBuilder firstReverse = new StringBuilder();
        for (int col = 0; col < n; col++) {
            first.append(grid[0][col]);
            firstReverse.append(1 - grid[0][col]);
        }

        // validate other rows string, is equal to (first row's string, or reverse string)
        // if not return false
        for (int i = 1; i < m; i++) {
            StringBuilder str = new StringBuilder();
            for (int j = 0; j < n; j++) {
                str.append(grid[i][j]);
            }

            String cur = str.toString();
            if (!cur.equals(first.toString()) && !cur.equals(firstReverse.toString())) {
                return false;
            }
        }
        return true;
    }
}

/*
Return true if it is possible to remove all 1's from grid using any number of operations or false otherwise.


110 -> 001

010
101

110
001
010

row flips or col flips

want all zeros, only happen in only has two patter in a matrix

normal or reverse pater, just 2

T: O(mn)
S: O(1)

*/

Last updated