Maximum XOR value in matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a matrix of size n X n. Our task is to create a program that will calculate the maximum XOR value of a complete row or a complete column.

Let’s take an example to understand the problem,

Input

N = 3
mat[N][N] = {{4, 9, 1}
{2, 8, 3}
{10, 12, 11}}

Output

13

Explanation

Row1: 4^9^1 = 12
Row2: 2^8^3 = 9
Row3: 10^12^11 = 13
Col1: 4^2^10 = 12
Col2: 9^8^12 = 13
Col3: 1^3^11 = 9

Here, we have calculated the XOR of all rows and columns and then the maximum of them is printed.

To solve this problem, we will calculate the XOR of all rows and columns of the matrix and find the maximum of them.

One way of finding the XOR of rows and columns is iterating the matrix 2 times, one for columns and other for rows.

But we can do the same using one iteration over the square matrix. And one for row-wise and other for column-wise.

This can be done using the same iteration by using matrix[i][j] for traversing row-wise matrix[j][i] for traversing column-wise

Example

Program to show illustrate our solution,

 Live Demo

#include<iostream>
using namespace std;
const int MAX = 1000;
int maxRCXOR(int mat[][MAX], int N){
   int rowXOR, colXOR;
   int maxXOR = 0;
   for (int i = 0 ; i < N ; i++){
      rowXOR = 0, colXOR = 0;
      for (int j = 0 ; j < N ; j++){
         rowXOR = rowXOR^mat[i][j];
         colXOR = colXOR^mat[j][i];
      }
      if (maxXOR < max(rowXOR, colXOR))
         maxXOR = max(rowXOR, colXOR);
      }
      return maxXOR;
}
int main() {
   int N = 3;
   int matrix[][MAX]= {
      {4, 9, 1},
      {2, 8, 3},
      {10, 12, 11}
   };
   cout<<"Maximum XOR of all row XOR and Column XOR is "<<maxRCXOR(matrix,N);
   return 0;
}

Output

Maximum XOR of all row XOR and Column XOR is 13
raja
Published on 10-Feb-2020 14:31:37
Advertisements