MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / GraphUnweightedUndirected

Class GraphUnweightedUndirected

Graphs/DepthFirstSearchRecursive.js:1–42  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class 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)) {
15 this.addNode(node1)
16 }
17 if (!(node2 in this.connections)) {
18 this.addNode(node2)
19 }
20 this.connections[node1].add(node2)
21 this.connections[node2].add(node1)
22 }
23
24 DFSRecursive(node, value, visited = new Set()) {
25 // DFS Function to search if a node with the given value is present in the graph
26 // checking if the searching node has been found
27 if (node === value) {
28 return true
29 }
30 // adding the current node to the visited set
31 visited.add(node)
32 // calling the helper function recursively for all unvisited nodes
33 for (const neighbour of this.connections[node]) {
34 if (!visited.has(neighbour)) {
35 if (this.DFSRecursive(neighbour, value, visited)) {
36 return true
37 }
38 }
39 }
40 return false
41 }
42}
43
44export { GraphUnweightedUndirected }
45

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected