From 1338a99eacb12134b74c775f7174999711ed49d0 Mon Sep 17 00:00:00 2001 From: trungnotchung Date: Mon, 28 Oct 2024 15:56:33 +0700 Subject: [PATCH] #204 fix: BFS implementation --- packages/object/src/hashgraph/index.ts | 49 +++++++++++++------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/packages/object/src/hashgraph/index.ts b/packages/object/src/hashgraph/index.ts index 95e1a412..df504add 100644 --- a/packages/object/src/hashgraph/index.ts +++ b/packages/object/src/hashgraph/index.ts @@ -223,47 +223,46 @@ 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(V), Space complexity: O(V) + areCausallyRelatedUsingBFS(hash1: Hash, hash2: Hash): boolean { + return ( + this._areCausallyRelatedUsingBFS(hash1, hash2) || + this._areCausallyRelatedUsingBFS(hash2, hash1) + ); + } + // Time complexity: O(1), Space complexity: O(1) getFrontier(): Hash[] { return Array.from(this.frontier);