diff --git a/packages/object/src/hashgraph/index.ts b/packages/object/src/hashgraph/index.ts index 95e1a412..760b0064 100644 --- a/packages/object/src/hashgraph/index.ts +++ b/packages/object/src/hashgraph/index.ts @@ -223,48 +223,45 @@ export class HashGraph { return test1 || test2; } - // Time complexity: O(V), Space complexity: O(V) - areCausallyRelatedUsingBFS(hash1: Hash, hash2: Hash): boolean { + private _areCausallyRelatedUsingBFS(start: Hash, target: Hash): boolean { const visited = new Set(); - const stack = [hash1]; - - while (stack.length > 0) { - const current = stack.pop(); - if (current === hash2) return true; - if (current === undefined) continue; - visited.add(current); + const queue: Hash[] = []; + let head = 0; - const vertex = this.vertices.get(current); - if (!vertex) continue; - for (const dep of vertex.dependencies) { - if (!visited.has(dep)) { - stack.push(dep); - } - } - } + queue.push(start); - visited.clear(); - stack.push(hash2); + while (head < queue.length) { + const current = queue[head]; + head++; - while (stack.length > 0) { - const current = stack.pop(); - if (current === hash1) return true; + if (current === target) return true; if (current === undefined) continue; - visited.add(current); + visited.add(current); const vertex = this.vertices.get(current); if (!vertex) continue; + for (const dep of vertex.dependencies) { if (!visited.has(dep)) { - stack.push(dep); + queue.push(dep); } } - } + if (head > queue.length / 2) { + queue.splice(0, head); + head = 0; + } + } return false; } - // Time complexity: O(1), Space complexity: O(1) + areCausallyRelatedUsingBFS(hash1: Hash, hash2: Hash): boolean { + return ( + this._areCausallyRelatedUsingBFS(hash1, hash2) || + this._areCausallyRelatedUsingBFS(hash2, hash1) + ); + } + getFrontier(): Hash[] { return Array.from(this.frontier); }