
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Each Diagonal Elements in Ascending Order of a Matrix in C++
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 −
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, 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
#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, ],]