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 C++ 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 firstname.lastname@example.org. 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.
- Count of arrays in which all adjacent elements are such that one of them divide the another
- Top 20 Dynamic Programming Interview Questions
- Subset with sum divisible by m
- Count ways to increase LCS length of two strings by one
- Number of subsequences of the form a^i b^j c^k
- Count of AP (Arithmetic Progression) Subsequences in an array
- Sum of matrix in which each element is absolute difference of its row and column numbers
- Check horizontal and vertical symmetry in binary matrix
- Find Maximum dot product of two arrays with insertion of 0's
- Probability of Knight to remain in the chessboard
- Number of palindromic paths in a matrix
- Find the largest rectangle of 1's with swapping of columns allowed
- Minimum Cost Polygon Triangulation
- Maximum sum rectangle in a 2D matrix | DP-27
- Palindrome Partitioning | DP-17