The Wayback Machine - https://web.archive.org/web/20220105223127/https://www.geeksforgeeks.org/rearrange-given-matrix-by-replacing-matij-with-mat-matij-matji/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Rearrange given Matrix by replacing mat[i][j] with mat[ mat[i][j] ][ mat[j][i] ]

  • Last Updated : 05 Jan, 2022

Given a square matrix mat[][] of order N containing integers in range [0, N), the task is to rearrange the matrix elements in the given manner. Replace the element at mat[i][j] with the element at mat[x][y] where x is the number at mat[i][j] and y is the number at mat[j][i]. 

Examples: 

Resolution Days 2022 GeeksforGeeks

Input: mat[][] = {{1, 3, 0, 4, 2},
                           {0, 1, 2, 3, 4},
                           {3, 4, 2, 1, 0},
                           {4, 1, 0, 2, 2},
                           {0, 1, 2, 1, 0}}
Output: 1 4 4 0 3 
              4 1 0 1 1 
              4 2 2 0 0 
              0 3 3 2 4 
              0 4 3 2 1
Explanation: mat[0][1] is replaced by mat[3][0] = 4, because,
x = mat[0][1] = 3, y = mat[1][0] = 0 and mat[x][y] = mat[3][0] = 4.
And similar for all other positions. 

Input: mat[][] = {{0, 1, 1},
                          {2, 1, 2},
                          {0, 2, 0}}
Output:  0 2 2 
               2 1 0 
               1 0 0 



 

Approach: The idea is to go as per the requirement of the problem. Traverse the matrix row-wise and find the element at mat[i][j] and mat[j][i]. Use these numbers x and y as the coordinates to get the replacement value for mat[i][j].

Below is the implementation of the above approach: 

C++




// C++ code to rearrange the matrix
// in specified manner.
#include <bits/stdc++.h>
using namespace std;
  
const int N = 5;
  
// Function to print matrix.
void showMatrix(int mat[][N])
{
    int i, j;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            cout << mat[i][j] << " ";
        }
        cout << endl;
    }
}
  
// Function to rearrange the matrix
// in specified manner.
void RearrangeMatrix(int mat[][N])
{
    int x, y, i, j;
    for (i = 0; i < N; i++) {
        for (j = 0; j < N; j++) {
            x = mat[i][j];
            y = mat[j][i];
            cout << mat[x][y] << " ";
        }
        cout << "\n";
    }
}
  
// Driver code
int main()
{
    int mat[][N] = { { 1, 3, 0, 4, 2 },
                     { 0, 1, 2, 3, 4 },
                     { 3, 4, 2, 1, 0 },
                     { 4, 1, 0, 2, 2 },
                     { 0, 1, 2, 1, 0 } };
  
    RearrangeMatrix(mat);
    return 0;
}
Output
1 4 4 0 3 
4 1 0 1 1 
4 2 2 0 0 
0 3 3 2 4 
0 4 3 2 1 

Time Complexity: O(N2)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!