Sort the Matrix Diagonally in C++

C++Server Side ProgrammingProgramming

Suppose we have N x M matrix, we have to sort this diagonally in increasing order from top-left to the bottom right. So if the matrix is like −

3311
2212
1112

The output matrix will be −

1111
1222
1233

To solve this, we will follow these steps −

  • Define a method called solve(), this will take si, sj and matrix mat

  • n := number of rows and m := number of columns

  • make an array called temp

  • i:= si and j := sj, and index := 0

  • while i < n and j < m

    • insert m[i, j] into temp, then increase i and j by 1

  • sort temp array

  • set index := 0, i := si and j := sj

  • while i < n and j < m

    • mat[i, j] := temp[index]

    • increase i, j and index by 1

  • from the main method, do the following −

  • n := number of rows and m := number of columns

  • for i in range 0 to n – 1

    • solve(i, 0, mat)

  • for j in range 1 to m – 1

    • solve(0, j, mat)

  • return mat

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   void solve(int si, int sj, vector < vector <int> > &mat){
      int n = mat.size();
      int m = mat[0].size();
      vector <int> temp;
      int i = si;
      int j = sj;
      int idx = 0;
      while(i < n && j < m){
         temp.push_back(mat[i][j]);
         i++;
         j++;
      }
      sort(temp.begin(), temp.end());
      idx = 0;
      i = si;
      j = sj;
      while(i < n && j < m){
         mat[i][j] = temp[idx];
         i++;
         j++;
         idx++;
      }
   }
   vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
      int n = mat.size();
      int m = mat[0].size();
      for(int i = 0; i <n; i++){
         solve(i, 0, mat);
      }
      for(int j = 1; j < m; j++){
         solve(0, j, mat);
      }
      return mat;
   }
};
main(){
   vector<vector<int>> v = {{3,3,1,1},{2,2,1,2},{1,1,1,2}};
   Solution ob;
   print_vector(ob.diagonalSort(v));
}


Input

[[3,3,1,1],[2,2,1,2],[1,1,1,2]]

Output

[[1,1,1,1],[1,2,2,2],[1,2,3,3]]
raja
Published on 31-Mar-2020 11:01:03
Advertisements