VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-flip-required-make-binary-matrix-symmetric/

⇱ Minimum flip required to make Binary Matrix symmetric - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum flip required to make Binary Matrix symmetric

Last Updated : 26 Dec, 2024

Given a Binary Matrix mat[][] of size n x n, consisting of 1s and 0s. The task is to find the minimum flips required to make the matrix symmetric along the main diagonal.

Examples :

Input: mat[][] = [[0, 0, 1],
[1, 1, 1],
[1, 0, 0]];
Output: 2
Value of mat[1][0] is not equal to mat[0][1].
Value of mat[2][1] is not equal to mat[1][2].
So, two flip are required.


Input: mat[][] = [[1, 1, 1, 1, 0],
[0, 1, 0, 1, 1],
[ 1, 0, 0, 0, 1],
[0, 1, 0, 1, 0],
[0, 1, 0, 0, 1]]
Output: 3

[Naive Approach] Using Matrix Transpose - O(n^2) Time and O(n^2) Space

The idea is to find the transpose of the matrix and find minimum number of flip required to make transpose and original matrix equal. To find minimum flip, find the number of position where original matrix and transpose matrix are not same, say x. So, our answer will be x/2.


Output
2

[Expected Approach] Comparing Lower and Upper Triangular Matrix - O(n^2) Time and O(1) Space

The idea is to find minimum flips required to make upper triangle of matrix equals to lower triangle of the matrix. To do so, we run two nested loop, outer loop from i = 0 to n i.e., for each row of the matrix and the inner loop from j = 0 to i, and check whether mat[i][j] is equal to mat[j][i]. Count of number of instances where they are not equal will be the minimum flips required to make matrix symmetric along main diagonal.


Output
2
Comment
Article Tags: