Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f34fd6d

Browse files
Added Connected Components using DFS (TheAlgorithms#223)
1 parent 4b2d6ac commit f34fd6d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

‎Graphs/ConnectedComponents.js‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
class GraphUnweightedUndirected {
2+
// Unweighted Undirected Graph class
3+
constructor () {
4+
this.connections = {}
5+
}
6+
7+
addNode (node) {
8+
// Function to add a node to the graph (connection represented by set)
9+
this.connections[node] = new Set()
10+
}
11+
12+
addEdge (node1, node2) {
13+
// Function to add an edge (adds the node too if they are not present in the graph)
14+
if (!(node1 in this.connections)) { this.addNode(node1) }
15+
if (!(node2 in this.connections)) { this.addNode(node2) }
16+
this.connections[node1].add(node2)
17+
this.connections[node2].add(node1)
18+
}
19+
20+
DFSComponent (components, node, visited) {
21+
// Helper function to populate the visited set with the nodes in each component
22+
23+
// adding the first visited node in the component to the array
24+
components.push(node)
25+
const stack = [node]
26+
// populating the visited set using DFS (Iterative)
27+
while (stack.length > 0) {
28+
const curr = stack.pop()
29+
visited.add(curr.toString())
30+
for (const neighbour of this.connections[curr].keys()) {
31+
if (!visited.has(neighbour.toString())) { stack.push(neighbour) }
32+
}
33+
}
34+
}
35+
36+
connectedComponents () {
37+
// Function to generate the Connected Components
38+
// Result is an array containing 1 node from each component
39+
const visited = new Set()
40+
const components = []
41+
for (const node of Object.keys(this.connections)) {
42+
if (!visited.has(node.toString())) { this.DFSComponent(components, node, visited) }
43+
}
44+
return components
45+
}
46+
}
47+
48+
function main () {
49+
const graph = new GraphUnweightedUndirected()
50+
graph.addEdge(1, 2) // Component 1
51+
graph.addEdge(3, 4) // Component 2
52+
graph.addEdge(3, 5) // Component 2
53+
console.log(graph.connectedComponents())
54+
}
55+
56+
main()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /