tstruct
Version:
Data structures & basic algorithms library
73 lines (72 loc) • 2.49 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.UnionFind = void 0;
var UnionFind = (function () {
function UnionFind() {
this._objectToId = new Map();
this._idToObject = new Map();
this._arr = [];
this._sizes = [];
this._numberOfComponents = 0;
}
Object.defineProperty(UnionFind.prototype, "numberOfComponents", {
get: function () {
return this._numberOfComponents;
},
enumerable: false,
configurable: true
});
UnionFind.prototype.add = function (item) {
if (this._objectToId.has(item))
return;
var itemId = this._arr.length;
this._arr.push(itemId);
this._sizes.push(1);
this._objectToId.set(item, itemId);
this._idToObject.set(itemId, item);
this._numberOfComponents++;
};
UnionFind.prototype.union = function (item1, item2) {
var item1Index = this.findIndex(item1);
var item2Index = this.findIndex(item2);
if (item1Index == item2Index)
return;
if (this._sizes[item1Index] <= this._sizes[item2Index]) {
this._arr[item1Index] = item2Index;
this._sizes[item2Index] =
this._sizes[item1Index] + this._sizes[item2Index];
}
else {
this._arr[item2Index] = item1Index;
this._sizes[item1Index] =
this._sizes[item1Index] + this._sizes[item2Index];
}
this._numberOfComponents--;
};
UnionFind.prototype.find = function (item) {
var itemId = this.findIndex(item);
return this._idToObject.get(itemId);
};
UnionFind.prototype.findIndex = function (item) {
var itemId = this._objectToId.get(item);
var root = itemId;
while (root != this._arr[root]) {
root = this._arr[root];
}
while (itemId != root) {
var next = this._arr[itemId];
this._arr[itemId] = root;
itemId = next;
}
return itemId;
};
UnionFind.prototype.size = function (item) {
var itemIndex = this.findIndex(item);
return this._sizes[itemIndex];
};
UnionFind.prototype.isConnected = function (item1, item2) {
return this.find(item1) == this.find(item2);
};
return UnionFind;
}());
exports.UnionFind = UnionFind;