⬅ Previous Topic
Accounts Merge Problem using Disjoint Set UnionNext Topic ⮕
Making a Large Island Using DSU⬅ Previous Topic
Accounts Merge Problem using Disjoint Set UnionNext Topic ⮕
Making a Large Island Using DSUTopic Contents
In this problem, you're given a 2D grid of size n × m
, initially filled with water (all cells are 0). You are also given k
operations where each operation turns a water cell into land (i.e., changes a 0 to 1). After each operation, you must return the number of islands in the grid.
An island is defined as a group of land cells (1s) that are connected horizontally or vertically.
Your task is to simulate each operation in order and return the number of islands after each.
class DSU {
constructor(n) {
this.parent = new Array(n).fill(0).map((_, i) => i);
this.rank = new Array(n).fill(0);
}
find(x) {
if (this.parent[x] !== x) {
this.parent[x] = this.find(this.parent[x]);
}
return this.parent[x];
}
union(x, y) {
let rootX = this.find(x);
let rootY = this.find(y);
if (rootX === rootY) return false;
if (this.rank[rootX] < this.rank[rootY]) {
this.parent[rootX] = rootY;
} else if (this.rank[rootX] > this.rank[rootY]) {
this.parent[rootY] = rootX;
} else {
this.parent[rootY] = rootX;
this.rank[rootX]++;
}
return true;
}
}
function numIslands2(n, m, operators) {
const dsu = new DSU(n * m);
const grid = Array.from({ length: n }, () => Array(m).fill(0));
const dirs = [[-1,0], [1,0], [0,-1], [0,1]];
const result = [];
let count = 0;
for (const [r, c] of operators) {
if (grid[r][c] === 1) {
result.push(count);
continue;
}
grid[r][c] = 1;
count++;
const id = r * m + c;
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < n && nc >= 0 && nc < m && grid[nr][nc] === 1) {
const nid = nr * m + nc;
if (dsu.union(id, nid)) {
count--;
}
}
}
result.push(count);
}
return result;
}
console.log(numIslands2(3, 3, [[0,0], [0,1], [1,2], [2,1]])); // Output: [1, 1, 2, 3]
⬅ Previous Topic
Accounts Merge Problem using Disjoint Set UnionNext Topic ⮕
Making a Large Island Using DSUYou 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.