-
Notifications
You must be signed in to change notification settings - Fork 3
/
1632.cpp
88 lines (84 loc) · 2.65 KB
/
1632.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class DisjointSet {
private:
vector<int> parent;
vector<int> rank;
int n;
public:
DisjointSet(int size) {
n = size;
parent.resize(size, 0);
rank.resize(size, 0);
for (int i = 0; i < size; i++) parent[i] = i;
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
bool merge(int x, int y) {
int gX = find(x);
int gY = find(y);
if (gX == gY) return false;
if (rank[gX] > rank[gY]) parent[gY] = gX;
else if (rank[gX] < rank[gY]) parent[gX] = gY;
else {
parent[gY] = gX;
rank[gX]++;
}
return true;
}
void reset() {
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
}
}
};
class Solution {
public:
vector<vector<int>> matrixRankTransform(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> answer(m, vector<int>(n, 1));
// mp:(sorted) value to positions
map<int, vector<pair<int, int>>> mp;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
mp[matrix[i][j]].push_back(make_pair(i, j));
}
}
vector<int> rowMax(m, 0);
vector<int> colMax(n, 0);
DisjointSet* disjointSet = new DisjointSet(m + n);
vector<vector<pair<int, int>>> group2positions(m + n);
for (auto& element : mp) {
disjointSet->reset();
group2positions.clear();
group2positions.resize(m + n);
// grouping positions with the same value by col and row
for (auto& [x, y] : element.second) {
disjointSet->merge(x, m + y);
}
// allocating the grouping results
for (auto& [x, y] : element.second) {
group2positions[disjointSet->find(x)].push_back(make_pair(x, y));
}
// for each group, assign the ranking
for (auto& group : group2positions) {
int rank = 1;
// rank should be the max among members in group
for (auto& [x, y] : group) {
rank = max(rank, max(rowMax[x], colMax[y]) + 1);
}
// update the answer and max rank in row and col
for (auto& [x, y] : group) {
answer[x][y] = rank;
rowMax[x] = rank;
colMax[y] = rank;
}
}
}
return answer;
}
};