![]() |
VOOZH | about |
Given a 2-D array of order N x N, print a matrix that is the mirror of the given tree across the diagonal. We need to print the result in a way: swap the values of the triangle above the diagonal with the values of the triangle below it like a mirror image swap. Print the 2-D array obtained in a matrix layout.
Examples:
Input : int mat[][] = {{1 2 4 }
{5 9 0}
{ 3 1 7}}
Output : 1 5 3
2 9 1
4 0 7
Input : mat[][] = {{1 2 3 4 }
{5 6 7 8 }
{9 10 11 12}
{13 14 15 16} }
Output : 1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
A simple solution to this problem involves extra space. We traverse all right diagonal (right-to-left) one by one. During the traversal of the diagonal, first, we push all the elements into the stack and then we traverse it again and replace every element of the diagonal with the stack element.
Below is the implementation of the above idea.
Output:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Time complexity :O(n2)
Auxiliary Space: O(n), as stack is used
An efficient solution to this problem is that if we observe an output matrix, then we notice that we just have to swap (mat[i][j] to mat[j][i]).
Below is the implementation of the above idea.
Implementation:
Output:
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
Time complexity :O(n2)
Auxiliary Space: O(1)