Maximum XOR value in matrix in C++

C++Server Side ProgrammingProgramming

Problem statement

Given a square matrix (N X N), the task is to find the maximum XOR value of a complete row or a complete column

Consider below matrix −

matrix[3][3] = {
   {1, 2, 4},
   {10, 4, 5},
   {1, 16, 4}
};
Output: 22

We get this maximum XOR value by doing XOR of elements in the second column (2 ^ 4 ^ 16) = 22

Algorithm

1. Start traverse the matrix and calculate XOR at each index row and column wise.
   We can compute both values by using indexes in reverse way. This is possible
   because matrix is a square matrix
2. Store the maximum of both

Example

#include<iostream>
using namespace std;
const int MAX = 1000;
int getMaxXOR(int matrix[][MAX], int n){
   int rowXOR, columnXOR;
   int maxXOR = 0;
   for (int i = 0 ; i < n ; ++i) {
      rowXOR = 0, columnXOR = 0;
      for (int j = 0 ; j < n ; ++j) {
         rowXOR = rowXOR^matrix[i][j];
         columnXOR = columnXOR^matrix[j][i];
      }
      if (maxXOR < max(rowXOR, columnXOR)) {
         maxXOR = max(rowXOR, columnXOR);
      }
   }
   return maxXOR;
}
int main(){
   int n = 3;
   int matrix[][MAX] = {
      {1 , 2, 4},
      {10 , 4, 5 },
      {1 , 16, 4}
   };
   cout << "Maximum XOR value = " << getMaxXOR(matrix, n) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Maximum XOR value = 22
raja
Published on 10-Feb-2020 10:01:37
Advertisements