From 4aea7969a7defa9a8a32e1c462c7751d97ef0568 Mon Sep 17 00:00:00 2001 From: Amit Batra <75168062+amitbatra31@users.noreply.github.com> Date: Sun, 9 Oct 2022 22:11:50 +0530 Subject: [PATCH] Add most stones removed --- Hacktoberfest2022/moststonesremoved.cpp | 73 +++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Hacktoberfest2022/moststonesremoved.cpp diff --git a/Hacktoberfest2022/moststonesremoved.cpp b/Hacktoberfest2022/moststonesremoved.cpp new file mode 100644 index 0000000..dc978e0 --- /dev/null +++ b/Hacktoberfest2022/moststonesremoved.cpp @@ -0,0 +1,73 @@ +class Solution +{ +public: + struct subset + { + int parent; + int rank; + }; + int find(vector &Parent, int x) + { + if (Parent[x].parent == -1) + { + return x; + } + return find(Parent, Parent[x].parent); + } + void Union(vector &Parent, int x, int y) + { + if (Parent[x].rank < Parent[y].rank) + { + Parent[x].parent = y; + } + else if (Parent[x].rank > Parent[y].rank) + { + Parent[y].parent = x; + } + else + { + Parent[y].parent = x; + Parent[x].rank++; + } + return; + } + bool isSameRow(vector> &stones, int i, int j) + { + return stones[i][0] == stones[j][0]; + } + bool isSameColumn(vector> &stones, int i, int j) + { + return stones[i][1] == stones[j][1]; + } + int removeStones(vector> &stones) + { + int n = stones.size(); + // vector> edges; + vector Parent(n, {-1, 0}); + for (int i = 0; i < n; i++) + { + for (int j = 0; j < i; j++) + { + if (isSameRow(stones, i, j) or isSameColumn(stones, i, j)) + { + int x = find(Parent, i); + int y = find(Parent, j); + if (x != y) + { + Union(Parent, x, y); + } + } + } + } + + int co = 0; + for (int i = 0; i < n; i++) + { + if (Parent[i].parent == -1) + { + co++; + } + } + return n - co; + } +}; \ No newline at end of file