Python Program to Interchange Diagonals of Matrix
Last Updated :
24 Jul, 2022
Given a square matrix of order n*n, you have to interchange the elements of both diagonals.
Examples :
Input : matrix[][] = {1, 2, 3,
4, 5, 6,
7, 8, 9}
Output : matrix[][] = {3, 2, 1,
4, 5, 6,
9, 8, 7}
Input : matrix[][] = {4, 2, 3, 1,
5, 7, 6, 8,
9, 11, 10, 12,
16, 14, 15, 13}
Output : matrix[][] = {1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
11, 14, 15, 16}
Explanation : Idea behind interchanging diagonals of a square matrix is simple. Iterate from 0 to n-1 and for each iteration you have to swap a[i][i] and a[i][n-i-1].
Python3
N = 3 ;
def interchangeDiagonals(array):
for i in range (N):
if (i ! = N / 2 ):
temp = array[i][i];
array[i][i] = array[i][N - i - 1 ];
array[i][N - i - 1 ] = temp;
for i in range (N):
for j in range (N):
print (array[i][j], end = " " );
print ();
if __name__ = = '__main__' :
array = [ 4 , 5 , 6 ],[ 1 , 2 , 3 ],[ 7 , 8 , 9 ];
interchangeDiagonals(array);
|
Output:
6 5 4
1 2 3
9 8 7
Time Complexity: O(N) where N is no of rows or columns; as we are using single loop for interchanging diagonals of a given matrix.
Auxiliary Space: O(1), as we are not using any extra space.
Please refer complete article on Program to Interchange Diagonals of Matrix for more details!
Share your thoughts in the comments
Please Login to comment...