Check horizontal and vertical symmetry in binary matrix in C++


Suppose we have a binary matrix of order M x N. The task is to check whether the matrix is horizontally symmetric, vertically symmetric or both. One matrix is said to be horizontally symmetric if the ith row is the same as the (M – i)th row, this is said to be vertically symmetric if the jth column is the same as the (N – j)th column. Suppose the input matrices are like below −

011
101
011

This is Horizontally symmetric.

111
101
111

This is Vertically symmetric.

111
101
111

This is Horizontally as well as vertically symmetric.

We will solve this problem using two phases. At first, we will check whether the matrix is horizontally symmetric or not, of so, then set one Boolean variable horizontal_flag = true, otherwise false, if the matrix is vertically symmetric, then set vartical_flag = true, otherwise false. Of both are true then the answer will be totally symmetric.

Example

 Live Demo

#include <iostream>
#define MAX 20
using namespace std;
void checkSymmetryLevel(int arr[][MAX], int N, int M) {
   bool horizontal_flag = true, vartical_flag = true;
   for (int i = 0, k = N - 1; i < N / 2; i++, k--) {
      for (int j = 0; j < M; j++) {
         if (arr[i][j] != arr[k][j]) {
            horizontal_flag = false;
            break;
         }
      }
   }
   for (int i = 0, k = M - 1; i < M / 2; i++, k--) {
      for (int j = 0; j < N; j++) {
         if (arr[i][j] != arr[k][j]) {
            vartical_flag = false;
            break;
         }
      }
   }
   if (!horizontal_flag && !vartical_flag)
      cout << "This is not symmetric from any point of view";
   else if (horizontal_flag && !vartical_flag)
      cout << "This is not horizontally symmetric";
   else if (vartical_flag && !horizontal_flag)
      cout << "This is vertically symmetric";
   else
   cout << "This is symmetric in both direction";
}
int main() {
   int mat[MAX][MAX] = {
   { 1, 1, 1 },
   { 1, 0, 1 },
   { 1, 1, 1 } };
   checkSymmetryLevel(mat, 3, 3);
}

Output

This is symmetric in both direction

Updated on: 22-Oct-2019

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements