Learn-dsa..in 30 days!



























CC-3 : Check if matrix is symmetric.

Description:

A matrix is symmetric, if it is equal to its transpose. This means all elements at index ( i , j )should be equal to the element at index ( j , i ). Given an input matrix mat. Check if the input matrix is symmetric.

Test cases and expected outputs:

Input Parameters Expected outputs
mat = { {1,4,5}, {4,1,3}, {5,3,1}}; The matrix is a Symmetric Matrix.
mat= { {0,1,1,0}, {1,1,1,1}, {0,1,1,0}} The matrix is *not* a Symmetric Matrix.
mat = { {1,1}, {1,1}, {1,1}, {1,1}}; The matrix is *not* a Symmetric Matrix.
mat= { {1,2,3,4}, {2,2,3,4}, {3,3,3,2}, {4,4,2,4}} The matrix is a Symmetric Matrix.

Pseudocode:

The java method should accept following input parameters: mat (integer matrix).
If mat does not have equal rows and columns, then mat is not a symmetric matrix, return false.
Iterate through mat using a for loop, using variable rIdx as loop counter. Loop variable rIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till rIdx < mat.length:
Iterate through mat using a for loop, using variable cIdx as loop counter. Loop variable cIdx will be initialized with value 0 and will iterate through all the matrix’s columns one by one till cIdx < mat[0].length:
If mat[rIdx][cIdx] != mat [cIdx][rIdx], return false else continue iterating.
If we have completed above loops without finding any unequal elements, return true, as the matrix is symmetric.

Code:

public boolean matArraySymmetricMatrix(int[][] mat) throws Exception{
	if (mat.length != mat[0].length) { return false; }
	for (int rIdx=0; rIdx < mat.length; rIdx++) {
		for (int cIdx=0; cIdx < mat[0].length; cIdx++) {
		   if (mat[rIdx][cIdx] != mat[cIdx][rIdx]) {
			   return false;
		   }
		 }
	}
	return true;
}

Click here to download and run code and test cases !