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

Class GraphUnweightedUndirected

Graphs/DepthFirstSearchIterative.js:1–45  ·  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 DFSIterative(node, value) {
25 // DFS Function to search if a node with the given value is present in the graph
26 const stack = [node]
27 const visited = new Set()
28 while (stack.length > 0) {
29 const currNode = stack.pop()
30 // if the current node contains the value being searched for, true is returned
31 if (currNode === value) {
32 return true
33 }
34 // adding the current node to the visited set
35 visited.add(currNode)
36 // adding neighbours in the stack
37 for (const neighbour of this.connections[currNode]) {
38 if (!visited.has(neighbour)) {
39 stack.push(neighbour)
40 }
41 }
42 }
43 return false
44 }
45}
46
47export { GraphUnweightedUndirected }
48

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected