Minimum cells to be flipped to get a 2 * 2 submatrix with equal elements | C ++ implementation of the approach ; Function to return the minimum flips required such that the submatrix from mat [ i ] [ j ] to mat [ i + 1 ] [ j + 1 ] contains all equal elements ; Function to return the minimum number of slips required such that the matrix contains at least a single submatrix of size 2 * 2 with all equal elements ; To store the result ; For every submatrix of size 2 * 2 ; Update the count of flips required for the current submatrix ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minFlipsSub ( string mat [ ] , int i , int j ) { int cnt0 = 0 , cnt1 = 0 ; if ( mat [ i ] [ j ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i ] [ j + 1 ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i + 1 ] [ j ] == '1' ) cnt1 ++ ; else cnt0 ++ ; if ( mat [ i + 1 ] [ j + 1 ] == '1' ) cnt1 ++ ; else cnt0 ++ ; return min ( cnt0 , cnt1 ) ; } int minFlips ( string mat [ ] , int r , int c ) { int res = INT_MAX ; for ( int i = 0 ; i < r - 1 ; i ++ ) { for ( int j = 0 ; j < c - 1 ; j ++ ) { res = min ( res , minFlipsSub ( mat , i , j ) ) ; } } return res ; } int main ( ) { string mat [ ] = { "0101" , "0101" , "0101" } ; int r = sizeof ( mat ) / sizeof ( string ) ; int c = mat [ 0 ] . length ( ) ; cout << minFlips ( mat , r , c ) ; return 0 ; }