Related Articles
Check if Bitwise AND of concatenation of diagonals exceeds that of middle row/column elements of a Binary Matrix
• Last Updated : 15 Apr, 2021

Given a binary matrix mat[][] of dimensions N * N, the task is to check if Bitwise AND of the decimal numbers obtained by concatenating primary and secondary diagonals elements is greater than the Bitwise AND of the decimal numbers obtained by the elements present in the middle row and column. If found to be true, then print “Yes”. Otherwise, print “No”.

Note: Concatenate matrix elements from left to right and top to bottom only. If N is even, then take the first middle row/column out of the two.

Examples:

Input: M[][] = {{1, 0, 1}, {0, 0, 1}, {0, 1, 1}}
Output: No
Explanation:
Number formed by concatenating principal diagonal elements is “101”.
Number formed by concatenating cross diagonal elements is “001”.
Number formed by concatenating elements in the middle row is “001”.
Number formed by concatenating elements in the middle column is “001”.
Therefore, the Bitwise AND of “101” and “001” is same as Bitwise AND of “001” and “001”.

Input: M[][] = {{0, 1, 1}, {0, 0, 0}, {0, 1, 1}}
Output: Yes

Naive Approach: The simplest approach to solve the problem is to traverse the given matrix and append the corresponding number to a variable, say P, if the current row is equal to the current column, to a variable, say S, if the row is N-column, to a variable,  say MR, if the row is equal to N/2, and to a variable, say MC, if the column is N/2. After completing the above steps, if Bitwise AND of P and S is greater than Bitwise AND of MR and MC, print “Yes”. Otherwise, print “No”.

Below is the implementation of the above approach:

## Java

 `// Java program for the above approach` `import` `java.util.ArrayList;` `import` `java.util.Collections;`   `// Java Program for above approach` `class` `GFG{` `    `  `// Function to convert obtained binary` `// representation to decimal value` `static` `int` `convert(ArrayList p)` `{` `    `  `    ``// Stores the resultant number` `    ``int` `ans = ``0``;` `    `  `    ``// Traverse string arr` `    ``for``(``int` `i: p)` `    ``{` `        ``ans = (ans << ``1``) | i;` `    ``}` `    `  `    ``// Return the number formed` `    ``return` `ans;` `}`   `// Function to count the number of` `// set bits in the number num` `static` `int` `count(``int` `num) ` `{` `    `  `    ``// Stores the count of set bits` `    ``int` `ans = ``0``;` `    `  `    ``// Iterate until num > 0` `    ``while` `(num > ``0``)` `    ``{` `        ``ans += num & ``1``;` `        ``num >>= ``1``;` `    ``}` `    ``return` `ans;` `}`   `// Function to check if the given matrix` `// satisfies the given condition or not` `static` `void` `checkGoodMatrix(``int` `mat[][])` `{` `    ``ArrayList P = ``new` `ArrayList();` `    ``ArrayList S = ``new` `ArrayList();` `    ``ArrayList MR = ``new` `ArrayList();` `    ``ArrayList MC = ``new` `ArrayList();` `    `  `    ``// To get P, S, MR, and MC` `    ``for``(``int` `i = ``0``; i < mat.length; i++)` `    ``{` `        ``for``(``int` `j = ``0``; j < mat[``0``].length; j++)` `        ``{` `            ``if` `(i == j)` `                ``P.add(mat[i][j]);`   `            ``if` `(i + j == mat.length - ``1``)` `                ``S.add(mat[i][j]);`   `            ``if` `(i == Math.floor((mat.length - ``1``) / ``2``))` `                ``MR.add(mat[i][j]);`   `            ``if` `(j == Math.floor((mat.length - ``1``) / ``2``))` `                ``MC.add(mat[i][j]);` `        ``}` `    ``}` `    ``Collections.reverse(S);`   `    ``// Stores decimal equivalents` `    ``// of binary representations` `    ``int` `P0 = convert(P);` `    ``int` `S0 = convert(S);` `    ``int` `MR0 = convert(MR);` `    ``int` `MC0 = convert(MC);`   `    ``// Gett the number of set bits` `    ``int` `setBitsPS = count((P0 & S0));` `    ``int` `setBitsMM = count((MR0 & MC0));` `    `  `    ``// Print the answer` `    ``if` `(setBitsPS > setBitsMM)` `       ``System.out.print(``"Yes"``);` `    ``else` `        ``System.out.print(``"No"``);` `}`   `// Driver code` `public` `static` `void` `main(String[] args) ` `{` `    ``int` `mat[][] = { { ``1``, ``0``, ``1` `},` `                    ``{ ``0``, ``0``, ``1` `},` `                    ``{ ``0``, ``1``, ``1` `} };` `    ``checkGoodMatrix(mat);` `}` `}`   `// This code is contributed by abhinavjain194`

## Python3

 `# Python3 program for the above approach`   `# Functio to convert obtained binary` `# representation to decimal value` `def` `convert(arr):` `  `  `      ``# Stores the resultant number` `    ``ans ``=` `0` `    `  `    ``# Traverse string arr` `    ``for` `i ``in` `arr:` `        ``ans ``=` `(ans << ``1``) | i` `        `  `    ``# Return the number formed` `    ``return` `ans`   `# Function to count the number of` `# set bits in the number num` `def` `count(num):` `  `  `    ``# Stores the count of set bits` `    ``ans ``=` `0` `    `  `    ``# Iterate until num > 0` `    ``while` `num:` `        ``ans ``+``=` `num & ``1` `        ``num >>``=` `1` `    ``return` `ans`   `# Function to check if the given matrix` `# satisfies the given condition or not` `def` `checkGoodMatrix(mat):` `    ``P ``=` `[]` `    ``S ``=` `[]` `    ``MR ``=` `[]` `    ``MC ``=` `[]`   `    ``# To get P, S, MR, and MC` `    ``for` `i ``in` `range``(``len``(mat)):` `        ``for` `j ``in` `range``(``len``(mat[``0``])):`   `            ``if` `i ``=``=` `j:` `                ``P.append(mat[i][j])`   `            ``if` `i ``+` `j ``=``=` `len``(mat)``-``1``:` `                ``S.append(mat[i][j])`   `            ``if` `i ``=``=` `(``len``(mat)``-``1``)``/``/``2``:` `                ``MR.append(mat[i][j])`   `            ``if` `j ``=``=` `(``len``(mat)``-``1``)``/``/``2``:` `                ``MC.append(mat[i][j])`   `    ``S.reverse()`   `    ``# Stores decimal equivalents` `    ``# of binary representations` `    ``P ``=` `convert(P)` `    ``S ``=` `convert(S)` `    ``MR ``=` `convert(MR)` `    ``MC ``=` `convert(MC)`   `    ``# Gett the number of set bits` `    ``setBitsPS ``=` `count(P & S)` `    ``setBitsMM ``=` `count(MR & MC)`   `    ``# Print the answer` `    ``if` `setBitsPS > setBitsMM:` `        ``print``(``"Yes"``)` `    ``else``:` `        ``print``(``"No"``)`   `# Driver Code`   `# Given Matrix` `mat ``=` `[[``1``, ``0``, ``1``], [``0``, ``0``, ``1``], [``0``, ``1``, ``1``]]`   `checkGoodMatrix(mat)`

## C#

 `// C# program for the above approach` `using` `System;` `using` `System.Collections.Generic;`   `class` `GFG{`   `// Function to convert obtained binary` `// representation to decimal value` `static` `int` `convert(List<``int``> p)` `{` `    `  `    ``// Stores the resultant number` `    ``int` `ans = 0;`   `    ``// Traverse string arr` `    ``foreach``(``int` `i ``in` `p) ` `    ``{ ` `        ``ans = (ans << 1) | i; ` `    ``}`   `    ``// Return the number formed` `    ``return` `ans;` `}`   `// Function to count the number of` `// set bits in the number num` `static` `int` `count(``int` `num)` `{` `    `  `    ``// Stores the count of set bits` `    ``int` `ans = 0;`   `    ``// Iterate until num > 0` `    ``while` `(num > 0) ` `    ``{` `        ``ans += num & 1;` `        ``num >>= 1;` `    ``}` `    ``return` `ans;` `}`   `// Function to check if the given matrix` `// satisfies the given condition or not` `static` `void` `checkGoodMatrix(``int``[, ] mat)` `{` `    ``List<``int``> P = ``new` `List<``int``>();` `    ``List<``int``> S = ``new` `List<``int``>();` `    ``List<``int``> MR = ``new` `List<``int``>();` `    ``List<``int``> MC = ``new` `List<``int``>();`   `    ``// To get P, S, MR, and MC` `    ``for``(``int` `i = 0; i < mat.GetLength(0); i++) ` `    ``{` `        ``for``(``int` `j = 0; j < mat.GetLength(1); j++) ` `        ``{` `            ``if` `(i == j)` `                ``P.Add(mat[i, j]);`   `            ``if` `(i + j == mat.GetLength(0) - 1)` `                ``S.Add(mat[i, j]);`   `            ``if` `(i == Math.Floor(` `                ``(mat.GetLength(0) - 1) / 2.0))` `                ``MR.Add(mat[i, j]);`   `            ``if` `(j == Math.Floor(` `                ``(mat.GetLength(0) - 1) / 2.0))` `                ``MC.Add(mat[i, j]);` `        ``}` `    ``}` `    ``S.Reverse();`   `    ``// Stores decimal equivalents` `    ``// of binary representations` `    ``int` `P0 = convert(P);` `    ``int` `S0 = convert(S);` `    ``int` `MR0 = convert(MR);` `    ``int` `MC0 = convert(MC);`   `    ``// Gett the number of set bits` `    ``int` `setBitsPS = count((P0 & S0));` `    ``int` `setBitsMM = count((MR0 & MC0));`   `    ``// Print the answer` `    ``if` `(setBitsPS > setBitsMM)` `        ``Console.Write(``"Yes"``);` `    ``else` `        ``Console.Write(``"No"``);` `}`   `// Driver code` `public` `static` `void` `Main(``string``[] args)` `{` `    ``int``[,] mat = { { 1, 0, 1 }, ` `                   ``{ 0, 0, 1 }, ` `                   ``{ 0, 1, 1 } };` `                   `  `    ``checkGoodMatrix(mat);` `}` `}`   `// This code is contributed by ukasp`

Output:

`No`

Time Complexity: O(N2)
Auxiliary Space: O(N)

Efficient approach: To optimize the above approach, the above approach can be optimized by traversing on each element’s diagonals, middle row, and middle column only. Follow the steps below to solve the problem:

• Initialize auxiliary vectors, say P, S, MR, and MC to store the connected elements of the main diagonal, cross diagonal, mid-row, and mid-column respectively.
• Iterate over the range [0, N – 1]:
• Append the element at (i, i) to P, i.e., main diagonal.
• Append the element at (N – 1 – i, i) to S, i.e., cross diagonal.
• Append the element at ((N-1)/2, i) to MR, i.e., mid-row.
• Append the element at ((N-1)/2, i) to MC, i.e., mid-column.
• Iterate over the range [0, N – 1]:
• Check if P[i] & S[i] > MR[i] & MC[i], then print “Yes” and return.
• Otherwise, check if p[i] & s[i] < MR[i] & MC[i], then print “No” and return.
• If none of the above conditions satisfy, then print “No”.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Function to check if the matrix` `// satisfy the given condition or not` `void` `checkGoodMatrix(` `    ``vector > M, ``int` `N)` `{` `    ``// Stores the binary representation` `    ``vector<``int``> p, s, MR, MC;`   `    ``// Iterate over the range [0, N]` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// Push element of main diagonal` `        ``p.push_back(M[i][i]);`   `        ``// Push element of cross diagona` `        ``s.push_back(M[N - 1 - i][i]);`   `        ``// Push element of Mid row` `        ``MR.push_back(M[(N - 1) / 2][i]);`   `        ``// Push element of Mid column` `        ``MC.push_back(M[i][(N - 1) / 2]);` `    ``}`   `    ``// Check if S & P > MR & MC` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``if` `(p[i] & s[i] > MR[i] & MC[i]) {` `            ``cout << ``"Yes"``;` `            ``return``;` `        ``}` `        ``else` `if` `(p[i] & s[i] < MR[i] & MC[i]) {` `            ``cout << ``"No"``;` `            ``return``;` `        ``}` `    ``}`   `    ``cout << ``"No"``;` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given matrix` `    ``vector > M{ { 0, 1, 1 },` `                            ``{ 0, 0, 0 },` `                            ``{ 0, 1, 1 } };`   `    ``// Size of the matrix` `    ``int` `N = M.size();`   `    ``checkGoodMatrix(M, N);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.util.Vector;`   `class` `GFG{`   `static` `void` `checkGoodMatrix(``int``[][] M, ``int` `N)` `{` `    `  `    ``// Stores the binary representation` `    ``Vector p = ``new` `Vector();` `    ``Vector s = ``new` `Vector();` `    ``Vector MR = ``new` `Vector();` `    ``Vector MC = ``new` `Vector();`   `    ``// Iterate over the range [0, N]` `    ``for``(``int` `i = ``0``; i < N; i++) ` `    ``{` `        `  `        ``// Push element of main diagonal` `        ``p.add(M[i][i]);`   `        ``// Push element of cross diagona` `        ``s.add(M[N - ``1` `- i][i]);`   `        ``// Push element of Mid row` `        ``MR.add(M[(N - ``1``) / ``2``][i]);`   `        ``// Push element of Mid column` `        ``MC.add(M[i][(N - ``1``) / ``2``]);` `    ``}`   `    ``// Check if S & P > MR & MC` `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `        ``int` `P = p.get(i);` `        ``int` `S = s.get(i);` `        ``int` `Mr = MR.get(i);` `        ``int` `Mc = MC.get(i);`   `        ``if` `((P & S) > (Mr & Mc))` `        ``{` `            ``System.out.print(``"Yes"``);` `            ``return``;` `        ``}` `        ``else` `if` `((P & S) < (Mr & Mc))` `        ``{` `            ``System.out.print(``"No"``);` `            ``return``;` `        ``}` `    ``}` `    ``System.out.print(``"No"``);` `}`   `// Driver code` `public` `static` `void` `main(String[] args)` `{` `    `  `    ``// Given matrix` `    ``int``[][] M = { { ``0``, ``1``, ``1` `}, ` `                  ``{ ``0``, ``0``, ``0` `}, ` `                  ``{ ``0``, ``1``, ``1` `} };`   `    ``// Size of the matrix` `    ``int` `N = M.length;`   `    ``checkGoodMatrix(M, N);` `}` `}`   `// This code is contributed by abhinavjain194`

Output:

`Yes`

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :