Skip to content

Commit 323791e

Browse files
authored
Add cpp code to sort a matrix diagonally
1 parent 8f794b9 commit 323791e

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

leetcode/cpp/sort/1329.cpp

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Problem: https://leetcode.com/problems/sort-the-matrix-diagonally/
2+
3+
class Solution {
4+
public:
5+
6+
// HINT: Difference of j and i is constant across a diagonal.
7+
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
8+
9+
int n = mat.size();
10+
if (n <=1) return mat;
11+
int m = mat[0].size();
12+
13+
map <int, vector<int>> mpp;
14+
map <int, int> mpp2;
15+
16+
for (int i=0 ; i<n ; i++) {
17+
for(int j=0 ; j<m ; j++) {
18+
19+
if(mpp.find(j-i)!=mpp.end()) {
20+
21+
vector<int> v = mpp[j-i];
22+
v.push_back(mat[i][j]);
23+
mpp[j-i] = v;
24+
} else {
25+
26+
vector<int> v;
27+
v.push_back(mat[i][j]);
28+
mpp[j-i] = v;
29+
}
30+
31+
}
32+
}
33+
34+
for (auto it: mpp) {
35+
36+
vector<int> v = it.second;
37+
sort(v.begin(), v.end());
38+
mpp[it.first] = v;
39+
mpp2[it.first] = 0;
40+
}
41+
42+
for (int i=0 ; i<n ; i++) {
43+
for(int j=0 ; j<m ; j++) {
44+
45+
int idx = mpp2[j-i];
46+
vector<int>v = mpp[j-i];
47+
mat[i][j] = v[idx];
48+
mpp2[j-i] = idx+1;
49+
}
50+
}
51+
52+
return mat;
53+
}
54+
};

0 commit comments

Comments
 (0)