| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MostStonesRemovedWithSameRowOrColumn; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MostStonesRemovedWithSameRowOrColumnUnionFind : IMostStonesRemovedWithSameRowOrColumn |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="stones"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int RemoveStones(int[][] stones) |
| 9 | 24 | | { |
| 9 | 25 | | var unionFind = new UnionFind(20002); |
| | 26 | |
|
| 139 | 27 | | foreach (var stone in stones) |
| 56 | 28 | | { |
| 56 | 29 | | unionFind.Union(stone[0], stone[1] + 10001); |
| 56 | 30 | | } |
| | 31 | |
|
| 9 | 32 | | return stones.Length - unionFind.ComponentCount; |
| 9 | 33 | | } |
| | 34 | |
|
| | 35 | | private class UnionFind |
| | 36 | | { |
| | 37 | | private readonly int[] _parent; |
| 9 | 38 | | private readonly HashSet<int> _uniqueNodes = []; |
| | 39 | |
|
| 9 | 40 | | public UnionFind(int n) |
| 9 | 41 | | { |
| 9 | 42 | | _parent = new int[n]; |
| | 43 | |
|
| 9 | 44 | | Array.Fill(_parent, -1); |
| 9 | 45 | | } |
| | 46 | |
|
| 247 | 47 | | public int ComponentCount { get; private set; } |
| | 48 | |
|
| | 49 | | private int Find(int node) |
| 169 | 50 | | { |
| 169 | 51 | | if (!_uniqueNodes.Contains(node)) |
| 66 | 52 | | { |
| 66 | 53 | | ComponentCount++; |
| | 54 | |
|
| 66 | 55 | | _uniqueNodes.Add(node); |
| 66 | 56 | | } |
| | 57 | |
|
| 169 | 58 | | if (_parent[node] == -1) |
| 112 | 59 | | { |
| 112 | 60 | | return node; |
| | 61 | | } |
| | 62 | |
|
| 57 | 63 | | return _parent[node] = Find(_parent[node]); |
| 169 | 64 | | } |
| | 65 | |
|
| | 66 | | public void Union(int x, int y) |
| 56 | 67 | | { |
| 56 | 68 | | var rootX = Find(x); |
| 56 | 69 | | var rootY = Find(y); |
| | 70 | |
|
| 56 | 71 | | if (rootX == rootY) |
| 3 | 72 | | { |
| 3 | 73 | | return; |
| | 74 | | } |
| | 75 | |
|
| 53 | 76 | | _parent[rootX] = rootY; |
| | 77 | |
|
| 53 | 78 | | ComponentCount--; |
| 56 | 79 | | } |
| | 80 | | } |
| | 81 | | } |