Java Program to check if a matrix is symmetric
Last Updated :
11 Jan, 2022
A square matrix is said to be symmetric matrix if the transpose of the matrix is same as the given matrix. Symmetric matrix can be obtain by changing row to column and column to row.
Examples:Â
Input : 1 2 3
2 1 4
3 4 3
Output : Yes
Input : 3 5 8
3 4 7
8 5 3
Output : No
A Simple solution is to do following.Â
1) Create transpose of given matrix.Â
2) Check if transpose and given matrices are same or not. Â
Java
import java.io.*;
class GFG {
static int MAX = 100 ;
static void transpose( int mat[][], int tr[][], int N)
{
for ( int i = 0 ; i < N; i++)
for ( int j = 0 ; j < N; j++)
tr[i][j] = mat[j][i];
}
static boolean isSymmetric( int mat[][], int N)
{
int tr[][] = new int [N][MAX];
transpose(mat, tr, N);
for ( int i = 0 ; i < N; i++)
for ( int j = 0 ; j < N; j++)
if (mat[i][j] != tr[i][j])
return false ;
return true ;
}
public static void main (String[] args)
{
int mat[][] = { { 1 , 3 , 5 },
{ 3 , 2 , 4 },
{ 5 , 4 , 1 } };
if (isSymmetric(mat, 3 ))
System.out.println( "Yes" );
else
System.out.println ( "No" );
}
}
|
Output :Â
Yes
Time Complexity : O(N x N)Â
Auxiliary Space : O(N x N)
An Efficient solution to check a matrix is symmetric or not is to compare matrix elements without creating a transpose. We basically need to compare mat[i][j] with mat[j][i]. Â
Java
import java.io.*;
class GFG {
static int MAX = 100 ;
static boolean isSymmetric( int mat[][], int N)
{
for ( int i = 0 ; i < N; i++)
for ( int j = 0 ; j < N; j++)
if (mat[i][j] != mat[j][i])
return false ;
return true ;
}
public static void main (String[] args)
{
int mat[][] = { { 1 , 3 , 5 },
{ 3 , 2 , 4 },
{ 5 , 4 , 1 } };
if (isSymmetric(mat, 3 ))
System.out.println( "Yes" );
else
System.out.println( "NO" );
}
}
|
Output:Â
Yes
Time Complexity : O(N x N)Â
Auxiliary Space : O(1)
Please refer complete article on Program to check if a matrix is symmetric for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...