Skip to content

Commit 08246c6

Browse files
committed
fix(Graph): breadth first path calculation
1 parent 9b9c8c3 commit 08246c6

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

utils/Graph/index.js

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,22 +72,27 @@ class Graph {
7272
}
7373

7474
doesPathExist(firstNode, secondNode) {
75-
const path = [];
75+
// https://stackoverflow.com/a/50575971
76+
const pathQueue = [];
7677
const visited = this.createVisitedObject();
7778
const q = [];
7879
visited[firstNode] = true;
7980
q.push(firstNode);
81+
pathQueue.push([firstNode]);
8082
while (q.length) {
81-
const node = q.pop();
82-
path.push(node);
83+
const node = q.shift();
84+
const path = pathQueue.shift();
85+
visited[node] = true;
86+
8387
const elements = this.AdjList.get(node);
8488
if (elements.includes(secondNode)) {
8589
return { path: [...path, secondNode], pathExists: true };
8690
}
8791
for (const elem of elements) {
8892
if (!visited[elem]) {
93+
pathQueue.push([...path, elem]);
94+
q.push(elem);
8995
visited[elem] = true;
90-
q.unshift(elem);
9196
}
9297
}
9398
}

0 commit comments

Comments
 (0)