Check if all rows of a Binary Matrix have all ones placed adjacently or not | Java 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
import java . util . * ; public class Main { static Boolean checkGroup ( Vector < Integer > arr ) { if ( arr . size ( ) <= 2 ) return true ; int corner = arr . get ( 0 ) + arr . get ( arr . size ( ) - 1 ) ; int xorSum = 0 ; for ( int i = 0 ; i < arr . size ( ) - 1 ; i ++ ) xorSum += ( arr . get ( i ) ^ arr . get ( i + 1 ) ) ; if ( corner == 0 ) if ( xorSum > 2 ) return false ; else if ( corner == 1 ) if ( xorSum > 1 ) return false ; else if ( xorSum > 0 ) return false ; return true ; } static Boolean isInGroupUtil ( int [ ] [ ] mat ) { for ( int i = 0 ; i < mat . length ; i ++ ) { Vector < Integer > arr = new Vector < Integer > ( ) ; for ( int j = 0 ; j < mat [ i ] . length ; j ++ ) { arr . add ( mat [ i ] [ j ] ) ; } if ( ! checkGroup ( arr ) ) return false ; } return true ; } static void isInGroup ( int [ ] [ ] mat ) { Boolean ans = isInGroupUtil ( mat ) ; if ( ans ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } public static void main ( String [ ] args ) { int [ ] [ ] mat = { { 0 , 1 , 1 , 0 } , { 1 , 1 , 0 , 0 } , { 0 , 0 , 0 , 1 } , { 1 , 1 , 1 , 0 } } ; isInGroup ( mat ) ; } }