|
| 1 | +/** |
| 2 | + * 947. Most Stones Removed with Same Row or Column |
| 3 | + * https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * On a 2D plane, we place n stones at some integer coordinate points. Each coordinate point may |
| 7 | + * have at most one stone. |
| 8 | + * |
| 9 | + * A stone can be removed if it shares either the same row or the same column as another stone |
| 10 | + * that has not been removed. |
| 11 | + * |
| 12 | + * Given an array stones of length n where stones[i] = [xi, yi] represents the location of the |
| 13 | + * ith stone, return the largest possible number of stones that can be removed. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[][]} stones |
| 18 | + * @return {number} |
| 19 | + */ |
| 20 | +var removeStones = function(stones) { |
| 21 | + const parent = new Map(); |
| 22 | + const find = (stoneIndex) => { |
| 23 | + if (!parent.has(stoneIndex)) { |
| 24 | + parent.set(stoneIndex, stoneIndex); |
| 25 | + } |
| 26 | + if (parent.get(stoneIndex) !== stoneIndex) { |
| 27 | + parent.set(stoneIndex, find(parent.get(stoneIndex))); |
| 28 | + } |
| 29 | + return parent.get(stoneIndex); |
| 30 | + }; |
| 31 | + |
| 32 | + const union = (stone1, stone2) => { |
| 33 | + parent.set(find(stone1), find(stone2)); |
| 34 | + }; |
| 35 | + |
| 36 | + const stoneMap = new Map(); |
| 37 | + for (let i = 0; i < stones.length; i++) { |
| 38 | + const [row, col] = stones[i]; |
| 39 | + const rowKey = `r${row}`; |
| 40 | + const colKey = `c${col}`; |
| 41 | + |
| 42 | + if (stoneMap.has(rowKey)) { |
| 43 | + union(i, stoneMap.get(rowKey)); |
| 44 | + } else { |
| 45 | + stoneMap.set(rowKey, i); |
| 46 | + } |
| 47 | + |
| 48 | + if (stoneMap.has(colKey)) { |
| 49 | + union(i, stoneMap.get(colKey)); |
| 50 | + } else { |
| 51 | + stoneMap.set(colKey, i); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + const uniqueGroups = new Set(); |
| 56 | + for (let i = 0; i < stones.length; i++) { |
| 57 | + uniqueGroups.add(find(i)); |
| 58 | + } |
| 59 | + |
| 60 | + return stones.length - uniqueGroups.size; |
| 61 | +}; |
0 commit comments