Swap diagonal elements in matrix
The problem involves swapping the diagonal elements of a given matrix. This means exchanging the values of the elements on the main diagonal (from topleft to bottomright) with the values of the elements on the secondary diagonal (from topright to bottomleft). This operation can be done using a recursive approach, which is what this a program demonstrates.
Problem Statement
Given an N x N matrix, we need to swap its diagonal elements using a recursive approach and display the resulting matrix.
Example
Consider the following matrix:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
After swapping the diagonal elements, the matrix becomes:
4 2 3 1
5 7 6 8
9 11 10 12
16 14 15 13
Idea to Solve the Problem
The idea to solve this problem is to use a recursive approach. We start by swapping the elements at the corners of the matrix (topleft and bottomright). Then, we move inwards towards the center of the matrix, swapping the corresponding elements from both diagonals. This process continues recursively until we've covered all the elements along the diagonals.
Algorithm
 Define a function
swapDiagonal
that takes the matrix and four indices (x
,y
,p
,q
) as parameters. These indices represent the topleft and bottomright corners of the current submatrix to be swapped.  If
x >= y
orp >= q
, it means we have finished swapping for the current submatrix, so return.  Swap the elements at
(x, p)
with(x, q)
and(y, p)
with(y, q)
.  Recursively call
swapDiagonal
with incrementedx
andy
, and decrementedp
andq
.  Display the matrix using the
showMatrix
function.  In the
main
function, define the input matrix and call theswapDiagonal
function with appropriate initial indices.  Display the original and modified matrices using the
showMatrix
function.
Code Solution

1) Interchange the diagonal of a matrix in java
2) Interchange the diagonal of a matrix in golang
3) Interchange the diagonal of a matrix in c
4) Interchange the diagonal of a matrix in c++
5) Interchange the diagonal of a matrix in c#
6) Interchange the diagonal of a matrix in vb.net
7) Interchange the diagonal of a matrix in node js
8) Interchange the diagonal of a matrix in python
9) Interchange the diagonal of a matrix in ruby
10) Interchange the diagonal of a matrix in php
11) Interchange the diagonal of a matrix in typescript
12) Interchange the diagonal of a matrix in scala
13) Interchange the diagonal of a matrix in swift
14) Interchange the diagonal of a matrix in kotlin
Time Complexity
The time complexity of this solution is O(N), where N is the number of elements in the matrix. This is because each element is swapped only once.
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment