Skip to content

Commit e20c998

Browse files
authored
Added DFS (Iterative) - Graph (#229)
1 parent 8e13280 commit e20c998

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Graphs/DepthFirstSearchIterative.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
DFSIterative (node, value) {
21+
// DFS Function to search if a node with the given value is present in the graph
22+
const stack = [node]
23+
const visited = new Set()
24+
while (stack.length > 0) {
25+
const currNode = stack.pop()
26+
// if the current node contains the value being searched for, true is returned
27+
if (currNode === value) { return true }
28+
// adding the current node to the visited set
29+
visited.add(currNode)
30+
// adding neighbours in the stack
31+
for (const neighbour of this.connections[currNode]) {
32+
if (!visited.has(neighbour)) {
33+
stack.push(neighbour)
34+
}
35+
}
36+
}
37+
return false
38+
}
39+
}
40+
41+
function main () {
42+
const graph = new GraphUnweightedUndirected()
43+
graph.addEdge(1, 2)
44+
graph.addEdge(2, 3)
45+
graph.addEdge(2, 4)
46+
graph.addEdge(3, 5)
47+
console.log(graph.DFSIterative(5, 1))
48+
console.log(graph.DFSIterative(5, 100))
49+
}
50+
51+
main()

0 commit comments

Comments
 (0)