Check if all rows of a Binary Matrix have all ones placed adjacently or not | C ++ program for the above approach ; Function to check if all 1 s are placed adjacently in an array or not ; Base Case ; Stores the sum of XOR of all pair of adjacent elements ; Calculate sum of XOR of all pair of adjacent elements ; Check for corner cases ; Return true ; Function to check if all the rows have all 1 s grouped together or not ; Traverse each row ; Check if all 1 s are placed together in the ith row or not ; Function to check if all 1 s in a row are grouped together in a matrix or not ; Print the result ; Driver Code ; Given matrix ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkGroup ( vector < int > arr ) { if ( arr . size ( ) <= 2 ) return true ; int corner = arr [ 0 ] + arr [ ( int ) arr . size ( ) - 1 ] ; int xorSum = 0 ; for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) xorSum += ( arr [ i ] ^ arr [ i + 1 ] ) ; if ( ! corner ) if ( xorSum > 2 ) return false ; else if ( corner == 1 ) if ( xorSum > 1 ) return false ; else if ( xorSum > 0 ) return false ; return true ; } bool isInGroupUtil ( vector < vector < int > > mat ) { for ( auto i : mat ) { if ( ! checkGroup ( i ) ) return false ; } return true ; } void isInGroup ( vector < vector < int > > mat ) { bool ans = isInGroupUtil ( mat ) ; if ( ans ) printf ( " Yes " ) ; else printf ( " No " ) ; } int main ( ) { vector < vector < int > > mat = { { 0 , 1 , 1 , 0 } , { 1 , 1 , 0 , 0 } , { 0 , 0 , 0 , 1 } , { 1 , 1 , 1 , 0 } } ; isInGroup ( mat ) ; }