-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathw-graphAlgorithms.js
47 lines (42 loc) · 1.06 KB
/
w-graphAlgorithms.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// const depthFirstPrint = (graph, source) => {
// const stack = [source];
// while (stack.length > 0) {
// const current = stack.pop();
// console.log(current);
// for (let direction of graph[current]) {
// stack.push(direction);
// }
// }
// };
// // recursive: depth first - for each
// const depthFirstPrint = (graph, source) => {
// console.log(source);
// return graph[source].forEach((d) => depthFirstPrint(graph, d));
// };
// // recursive:
// const depthFirstPrint = (graph, source) => {
// console.log(source);
// for (let neighbor of graph[source]) {
// depthFirstPrint(graph, neighbor);
// }
// };
// breadth first:
const depthFirstPrint = (graph, source) => {
const queue = [source];
while (queue.length > 0) {
let current = queue.shift();
console.log(current);
for (let neighbor of graph[current]) {
queue.push(neighbor);
}
}
};
const graph = {
a: ["b", "c"],
b: ["d"],
c: ["e"],
d: ["f"],
e: [],
f: [],
};
depthFirstPrint(graph, "a");