⬅ Previous Topic
Minimum Operations to Make Network ConnectedNext Topic ⮕
Accounts Merge Problem using Disjoint Set Union⬅ Previous Topic
Minimum Operations to Make Network ConnectedNext Topic ⮕
Accounts Merge Problem using Disjoint Set UnionTopic Contents
You are given n stones placed on a 2D plane, where each stone has a unique position represented by [x, y]
. A stone can be removed if there exists another stone in the same row or column.
The objective is to remove as many stones as possible under the given rule. Return the maximum number of stones that can be removed.
visited
set.total stones - number of components
as the final answer.function removeStones(stones) {
const adj = new Map();
// Build graph with row/col identifier trick to avoid collisions
for (const [x, y] of stones) {
const row = `r${x}`;
const col = `c${y}`;
if (!adj.has(row)) adj.set(row, []);
if (!adj.has(col)) adj.set(col, []);
adj.get(row).push(col);
adj.get(col).push(row);
}
const visited = new Set();
let components = 0;
function dfs(node) {
visited.add(node);
for (const neighbor of adj.get(node) || []) {
if (!visited.has(neighbor)) {
dfs(neighbor);
}
}
}
for (const [x, y] of stones) {
const node = `r${x}`;
if (!visited.has(node)) {
dfs(node);
components++;
}
}
return stones.length - components;
}
console.log(removeStones([[0,0],[0,1],[1,0],[1,2],[2,1],[2,2]])); // Output: 5
console.log(removeStones([[0,0],[0,2],[1,1],[2,0],[2,2]])); // Output: 3
console.log(removeStones([[0,0]])); // Output: 0
⬅ Previous Topic
Minimum Operations to Make Network ConnectedNext Topic ⮕
Accounts Merge Problem using Disjoint Set UnionYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.