Open In App

Check if all rows of a Binary Matrix have all ones placed adjacently or not

Last Updated : 16 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.


Java




// Java program for the above approach
import java.util.*;
public class Main
{
    // Function to check if all 1s are
    // placed adjacently in an array or not
    static Boolean checkGroup(Vector<Integer> arr)
    {
  
        // Base Case
        if (arr.size() <= 2)
            return true;
        int corner = arr.get(0) + arr.get(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.get(i) ^ arr.get(i + 1));
  
        // Check for corner cases
        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
        return true;
    }
  
    // Function to check if all the rows
    // have all 1s grouped together or not
    static Boolean isInGroupUtil(int[][] mat)
    {
  
        // Traverse each row
        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]);
            }
            // Check if all 1s are placed
            // together in the ith row or not
            if (!checkGroup(arr))
                return false;
             }
        return true;
    }
  
  
    // Function to check if all 1s in a row
    // are grouped together in a matrix or not
    static void isInGroup(int[][] mat)
    {
  
        Boolean ans = isInGroupUtil(mat);
  
        //Print the result
        if (ans)
            System.out.print("Yes");
        else
            System.out.print("No");
    }
     
    public static void main(String[] args) {
        // Given matrix
        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 decode2207.


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)


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to check if all 1s are
    // placed adjacently in an array or not
    static bool checkGroup(List<int> arr)
    {
   
        // Base Case
        if (arr.Count <= 2)
            return true;
        int corner = arr[0] + arr[arr.Count-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.Count - 1; i++)
            xorSum += (arr[i] ^ arr[i + 1]);
   
        // Check for corner cases
        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
        return true;
    }
   
    // Function to check if all the rows
    // have all 1s grouped together or not
    static bool isInGroupUtil(int[,] mat)
    {
   
        // Traverse each row
        for (int i = 0; i < mat.GetLength(1); i++)
        {
            List<int> arr = new List<int>();
            for(int j = 0; j < mat.GetLength(0); j++)
            {
                arr.Add(mat[i,j]);
            }
            // Check if all 1s are placed
            // together in the ith row or not
            if (!checkGroup(arr))
                return false;
            }
        return true;
    }
   
   
    // Function to check if all 1s in a row
    // are grouped together in a matrix or not
    static void isInGroup(int[,] mat)
    {
   
        bool ans = isInGroupUtil(mat);
   
        //Print the result
        if (ans)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
   
  // Driver code
  static void Main()
  {
     
    // Given matrix
    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 divyeshrabadiya07.


Javascript




<script>
    // Javascript program for the above approach
     
    // Function to check if all 1s are
    // placed adjacently in an array or not
    function checkGroup(arr)
    {
 
        // Base Case
        if (arr.length <= 2)
            return true;
        let corner = arr[0] + arr[arr.length-1];
 
        // Stores the sum of XOR of all
        // pair of adjacent elements
        let xorSum = 0;
 
        // Calculate sum of XOR of all
        // pair of adjacent elements
        for (let i = 0; i < arr.length - 1; i++)
            xorSum += (arr[i] ^ arr[i + 1]);
 
        // Check for corner cases
        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
        return true;
    }
 
    // Function to check if all the rows
    // have all 1s grouped together or not
    function isInGroupUtil(mat)
    {
 
        // Traverse each row
        for (let i = 0; i < mat.length; i++)
        {
            let arr = []
            for(let j = 0; j < mat[i].length; j++)
            {
                arr.push(mat[i][j]);
            }
            // Check if all 1s are placed
            // together in the ith row or not
            if (!checkGroup(arr))
                return false;
             }
        return true;
    }
 
 
    // Function to check if all 1s in a row
    // are grouped together in a matrix or not
    function isInGroup(mat)
    {
 
        let ans = isInGroupUtil(mat);
 
        //Print the result
        if (ans)
            document.write("Yes");
        else
            document.write("No");
    }
     
    // Given matrix
    let 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 mukesh07.
</script>


Output: 

Yes

 

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



Similar Reads

Count anagrams having first character as a consonant and no pair of consonants or vowels placed adjacently
Given a string S of length N, the task is to count the number of anagrams of S whose first character is a consonant and no pair of consonants or vowels are adjacent to each other. Examples: Input: S = "GADO"Output: 4Explanation:The anagrams of string S satisfying the given conditions are GADO, GODA, DOGA, DAGO.Therefore, the total number of such an
19 min read
Make all Ones together by Shifting Ones.
Given, a binary string contains zeroes and ones. In one operation you can move one step character '1' to either left or right. Find the minimum number of operations required to make all ones together without any intermediate zeroes. Examples: Input: 11011Output: 2Explanation: In the first operation move '1' at index 3 to index 2. Now the string bec
6 min read
Sort even-placed elements in increasing and odd-placed in decreasing order
We are given an array of n distinct numbers. The task is to sort all even-placed numbers in increasing and odd-placed numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers. Note that the first element is considered as even placed because of its index 0. Examples:
17 min read
Find size of the largest '+' formed by all ones in a binary matrix
Given a N X N binary matrix, find the size of the largest '+' formed by all 1s. Example: For above matrix, largest '+' would be formed by highlighted part of size 17. The idea is to maintain four auxiliary matrices left[][], right[][], top[][], bottom[][] to store consecutive 1’s in every direction. For each cell (i, j) in the input matrix, we stor
22 min read
Maximum Number of Ones in Binary Matrix
Given a binary matrix mat[][] with dimensions m * n, and any square sub-matrix of mat of size len * len has at most k ones. The task is to return the maximum possible number of ones that the matrix mat can have. Example: Input: m = 3, n = 3, len = 2, k = 1Output: 4Explanation: In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one. The best so
4 min read
Place N boys and M girls in different rows such that count of persons placed in each row is maximized
Given two integers N and M representing the number of boys and girls, the task is to arrange them in number of different rows of same size such that each row contains the maximum number of students possible and each row should contain either boys or girls.Note: No row can contain both boys and girls. Example: Input: N = 4, M = 2Output: 2Explanation
4 min read
Check if all objects of type A and B can be placed on N shelves
Given two integers A and B, representing the count of objects of two different types, and another integer N which represents the number of shelves, the task is to place all objects in the given N shelves abiding by the following rules: Any shelf cannot contain both Type-A and Type-B objects at the same time.No shelf can contain more than K objects
8 min read
Check if all disks can be placed at a single rod based on given conditions
Given an array arr[] consisting of N integers representing N rods each with a disk of radius arr[i], the task is to check if it is possible to move all disks to a single rod based on the condition that a disk at ith rod can be moved to jth rod only if: abs(i - j) = 1 and ith rod has only a single disk.The disk at ith rod has radii less than the top
6 min read
Program to check if a matrix is Binary matrix or not
Given a matrix, the task is to check if that matrix is a Binary Matrix. A Binary Matrix is a matrix in which all the elements are either 0 or 1. It is also called Logical Matrix, Boolean Matrix, Relation Matrix. Examples: Input: {{1, 0, 1, 1}, {0, 1, 0, 1} {1, 1, 1, 0}} Output: Yes Input: {{1, 0, 1, 1}, {1, 2, 0, 1}, {0, 0, 1, 1}} Output: No Approa
5 min read
Maximum number of ones in a N*N matrix with given constraints
Given two integers [Tex]n [/Tex]and [Tex]x [/Tex], where [Tex]x &lt;= n [/Tex]. Find the maximum number of one's in a [Tex]n * n [/Tex]binary matrix can have such that every sub-matrix of size [Tex]x * x [/Tex]has atleast one cell as zero. Examples: Input:5 3 Output: Maximum number of ones = 24 The matrix will be: 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1
5 min read