Sort the Matrix Diagonally in C++

C++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 −

 3 3 1 1 2 2 1 2 1 1 1 2

The output matrix will be −

 1 1 1 1 1 2 2 2 1 2 3 3

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]]
Updated on 29-Apr-2020 11:06:15