Minimum operations to convert Binary Matrix A to B by flipping submatrix of size K | C ++ program for the above approach ; Function to count the operations required to convert matrix A to B ; Store the sizes of matrix ; Stores count of flips required ; Traverse the iven matrix ; Check if the matrix values are not equal ; Increment the count of moves ; Check if the current square sized exists or not ; Flip all the bits in this square sized submatrix ; Count of operations required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minMoves ( vector < vector < char > > a , vector < vector < char > > b , int K ) { int n = a . size ( ) , m = a [ 0 ] . size ( ) ; int cntOperations = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] != b [ i ] [ j ] ) { cntOperations ++ ; if ( i + K - 1 >= n j + K - 1 >= m ) { return -1 ; } for ( int p = 0 ; p <= K - 1 ; p ++ ) { for ( int q = 0 ; q <= K - 1 ; q ++ ) { if ( a [ i + p ] [ j + q ] == '0' ) { a [ i + p ] [ j + q ] = '1' ; } else { a [ i + p ] [ j + q ] = '0' ; } } } } } } return cntOperations ; } int main ( ) { vector < vector < char > > A = { { '1' , '0' , '0' } , { '0' , '0' , '0' } , { '0' , '0' , '0' } } ; vector < vector < char > > B = { { '0' , '0' , '0' } , { '0' , '0' , '0' } , { '0' , '0' , '0' } } ; int K = 3 ; cout << minMoves ( A , B , K ) ; return 0 ; }