Check If the Given Two Matrices Are Mirror Images of One Another in JavaIn Java programming, determining if two matrices are mirror images of each other involves comparing corresponding elements in reverse order. A matrix is considered a mirror image of another if its rows or columns are reversed versions of the corresponding rows or columns in the other matrix. Examples of Matrices Mirror ImageExample 1: Input: Output: Yes Explanation:
All corresponding elements satisfy the mirror image condition; hence the output is "Yes". Example 2: Input: Output: No Explanation:
However, for i = 0 (first row): mat1[0][1] = 2, mat2[0][1] = 2 does not match (mat1[0][1] = 2, mat2[0][1] = 1) which does not satisfy the mirror image condition, hence the output is "No". Example 3: Input: Output: Yes Explanation:
All corresponding elements satisfy the mirror image condition, hence the output is "Yes". ApproachThe code checks if matrix2 is the horizontal mirror image of matrix1 by comparing each row of matrix1 with the corresponding row of matrix2 read from right to left. AlgorithmStep 1: Define a function checkMirror(matrix1, matrix2, size) to compare two square matrices matrix1 and matrix2 of size size x size. Step 2: Initialize row to 0 and col to 0 to track current indices in matrix2 and also initialize isMirrorImage to true as an initial assumption that matrices are mirror images. Step 3: Use an outer loop (i iterating over rows of matrix1):
Step 4: Reset col to 0 after completing the inner loop for each row comparison and Increment row to move to the next row in matrix2 for comparison with the next row in matrix1. Step 5: If isMirrorImage remains true, print "Yes" indicating matrix2 is a mirror image of matrix1. Otherwise, print "No" indicating they are not mirror images. Step 6: Define size as the size of the matrices (for example, 3 for 3x3 matrices).
ImplementationLet's implement the above algorithm in a Java program. File Name: MirrorImageCheck.java Output: Yes Time Complexity: The time complexity of the code is O(n^2), where n is the size of the matrix (assuming the matrix is n×n). Auxiliary Space: The auxiliary space of the code is O(1) |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India