Program to sort each diagonal elements in ascending order of a matrix in C++

ProgrammingPythonServer Side Programming

Suppose we have n x m matrix Mat, we have to sort this Mat diagonally in increasing order from top-left to the bottom right, so that all elements in the diagonals are sorted. So if the input 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, do

    • 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, do

    • solve(i, 0, mat)

  • for j in range 1 to m – 1, do

    • solve(0, j, mat)

  • return mat

Let us see the following implementation to get better understanding −

Example

 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 07-Oct-2020 12:31:06
Advertisements