Skip to content
Related Articles

Related Articles

Check if all rows of a Binary Matrix have all ones placed adjacently or not
  • Last Updated : 26 Feb, 2021

Given a binary matrix mat[][] of dimension N*M, the task is to check if all 1s in each row are placed adjacently on the given matrix. If all 1s in each row are adjacent, then print “Yes”. Otherwise, print “No”.

Examples:

Input: mat[][] = {{0, 1, 1, 0}, {1, 1, 0, 0}, {0, 0, 0, 1}, {1, 1, 1, 0}
Output: Yes
Explanation:
Elements in the first row are {0, 1, 1, 0}.
Elements in the 2nd row are {1, 1, 0, 0}.
Elements in the 3rd row are {0, 0, 0, 1}.
Elements in the 4th row are {1, 1, 1, 0}.
Therefore, all the rows have all 1s grouped together. Therefore, print Yes.

Input: mat[][] = {{1, 0, 1}, {0, 0, 1}, {0, 0, 0}}
Output: No

Approach: The idea is to perform row-wise traversal on the matrix and check if all the 1s in a row are placed adjacently or not by using the property of Bitwise XOR. The given problem can be solved based on the following observations:



  • Calculate the sum of Bitwise XOR of every pair of adjacent elements of ith row, say X. All 1s will be not together in the ith row if any of the following conditions are satisfied:
    • If X > 2 and mat[i][0] + mat[i][M – 1] = 0.
    • If X > 1 and mat[i][0] + mat[i][M – 1] = 1.
    • If X > 0 and mat[i][0] + mat[i][M – 1] = 0.

Follow the steps below to solve this problem:

  • Traverse the given matrix mat[][] and perform the following operations:
    • For each row, check if the value of M is less than 3, then print “Yes”.
    • Otherwise, find the sum of Bitwise XOR of adjacent array elements and store it in a variable, say X.
    • For every value of X, if any of the above-mentioned conditions holds true, then print “No”.
  • After completing the above steps, if any of the above conditions does not hold true for any value of X, then print “No”.

Below is the implementation of the above approach:

C++




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


Python3




# Python3 program for the above approach
 
# Function to check if all 1s are
# placed adjacently in an array or not
def checkGroup(arr):
 
    # Base Case
    if len(arr) <= 2:
        return True
 
    corner = arr[0] + arr[-1]
 
    # Stores the sum of XOR of all
    # pair of adjacent elements
    xorSum = 0
 
    # Calculate sum of XOR of all
    # pair of adjacent elements
    for i in range(len(arr)-1):
        xorSum += (arr[i] ^ arr[i + 1])
 
    # Check for corner cases
    if not corner:
        if xorSum > 2:
            return False
    elif corner == 1:
        if xorSum > 1:
            return False
    else:
        if xorSum > 0:
            return False
           
    # Return true
    return True
 
# Function to check if all the rows
# have all 1s grouped together or not
def isInGroupUtil(mat):
 
    # Traverse each row
    for i in mat:
 
        # Check if all 1s are placed
        # together in the ith row or not
        if not checkGroup(i):
            return False
 
    return True
 
# Function to check if all 1s in a row
# are grouped together in a matrix or not
def isInGroup(mat):
 
    ans = isInGroupUtil(mat)
     
    # Print the result
    if ans:
        print("Yes")
    else:
        print("No")
 
 
# Given matrix
mat = [[0, 1, 1, 0], [1, 1, 0, 0],
       [0, 0, 0, 1], [1, 1, 1, 0]]
 
# Function Call
isInGroup(mat)


Output: 

Yes

 

Time Complexity: O(N*M)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :