-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathw-graph-connectedComponentsCount.js
72 lines (59 loc) · 1.48 KB
/
w-graph-connectedComponentsCount.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// https://structy.net/problems/connected-components-count
// p: adjacency list
// r: num of connected components
// e:
// connectedComponentsCount({
// 0: [8, 1, 5],
// 1: [0],
// 5: [0, 8],
// 8: [0, 5],
// 2: [3, 4],
// 3: [2, 4],
// 4: [3, 2]
// }); // -> 2
// recursion:
const connectedComponentsCount = (graph) => {
let count = 0;
const visited = new Set();
for (let node in graph) {
if (travel(graph, node, visited)) count++;
}
console.log(count);
return count;
};
const travel = (graph, current, visited) => {
if (visited.has(current.toString())) return false;
visited.add(current.toString());
for (let neighbor of graph[current]) {
travel(graph, neighbor, visited);
}
return true;
};
// // DFS
// const connectedComponentsCount = (graph) => {
// const visited = new Set();
// let count = 0;
// const stack = [];
// for (const node in graph) {
// stack.push(node);
// }
// console.log(stack);
// while (stack.length > 0) {
// const current = stack.pop();
// visited.add(current.toString());
// for (const neighbor of graph[current]) {
// !visited.has(neighbor.toString()) && stack.push(neighbor.toString());
// }
// // console.log(current);
// // console.log(visited);
// }
// };
connectedComponentsCount({
0: [8, 1, 5],
1: [0],
5: [0, 8],
8: [0, 5],
2: [3, 4],
3: [2, 4],
4: [3, 2],
}); // -> 2