Given a binary matrix, the task is to find whether row swaps or column swaps give maximum size sub-matrix with all 1’s. In a row swap, we are allowed to swap any two rows. In a column swap we are allowed to swap any two columns. Output “Row Swap” or “Column Swap” and the maximum size.
Input : 1 1 1 1 0 1 Output : Column Swap 4 By swapping column 1 and column 2(0-based indexing), index (0, 0) to (1, 1) makes the largest binary sub-matrix. Input : 0 0 0 1 1 0 1 1 0 0 0 0 1 1 0 Output : Row Swap 6 Input : 1 1 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 1 1 0 Output : Row Swap 8
The idea is to find both row swap and column swap maximum size binary submatrix and compare.
To find the maximum sized binary sub-matrix with row swaps allowed, make a 2-D array, say dp[i][j]. Each value of dp[i][j] contains the number of consecutive 1s on right side of (i,j) in i-th row. Now, store each column in the 1-D temporary array one by one, say b and sort, and find maximum b[i] * (n – i), since b[i] is indicating the sub-matrix width and (n – i) is sub-matrix height.
Similarly, to find the maximum size binary sub-matrix with column swap allowed, find dp[i][j], where each value contains the number of consecutive 1 below the (i, j) in j-th column. Similarly, store each row in the 1-D temporary array one by one, say b and sort. Find maximum b[i] * (m – i), since b[i] is indicating the submatrix height and (n – i) is submatrix width.
Below is the implementation of this approach:
Row Swap 6
This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check if a grid can become row-wise and column-wise sorted after adjacent swaps
- Maximum size rectangle binary sub-matrix with all 1s
- Maximum value in a matrix which contain intersecting concentric submatrix
- Maximize the binary matrix by filpping submatrix once
- Check if matrix A can be converted to B by changing parity of corner elements of any submatrix
- Find column with maximum sum in a Matrix
- Find maximum element of each column in a matrix
- Replace every matrix element with maximum of GCD of row or column
- Check if sums of i-th row and i-th column are same in matrix
- Find pair with maximum difference in any column of a Matrix
- Find if a binary matrix exists with given row and column sums
- Check if the given matrix is increasing row and column wise
- Maximum size subset with given sum
- Size of The Subarray With Maximum Sum
- Maximum size square sub-matrix with all 1s