Skip to content

Commit

Permalink
#204 fix: BFS implementation (#208)
Browse files Browse the repository at this point in the history
Co-authored-by: Oak <[email protected]>
  • Loading branch information
trungnotchung and d-roak authored Oct 28, 2024
1 parent 965e534 commit 81b7de2
Showing 1 changed file with 23 additions and 26 deletions.
49 changes: 23 additions & 26 deletions packages/object/src/hashgraph/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Hash>();
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);
}
Expand Down

0 comments on commit 81b7de2

Please sign in to comment.