947. Most Stones Removed with Same Row or Column
https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/
/*
* @lc app=leetcode id=947 lang=cpp
*
* [947] Most Stones Removed with Same Row or Column
*/
// @lc code=start
class Solution {
public:
class UF {
public:
vector<int> parents;
UF(int N): parents(N) {
for (int i = 0; i < N; ++i) {
parents[i] = i;
}
}
int find(int x) {
while (x != parents[x]) {
x = parents[x];
parents[x] = parents[parents[x]];
}
return parents[x];
}
void un(int x, int y) {
x = find(x);
y = find(y);
if (x != y) parents[x] = y;
}
};
int removeStones(vector<vector<int>>& stones) {
const int k_size = 10000;
UF uf(k_size * 2);
for (const auto &s : stones) {
uf.un(s[0], s[1] + k_size);
}
unordered_set<int> visited;
for (const auto &s : stones) {
visited.insert(uf.find(s[0]));
}
return stones.size() - visited.size();
}
};
// @lc code=end
Last updated