Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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 −

0 1 1
1 0 1
0 1 1

This is Horizontally symmetric.

1 1 1
1 0 1
1 1 1

This is Vertically symmetric.

1 1 1
1 0 1
1 1 1

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: 2019-10-22T07:46:03+05:30

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements