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 b5899d5

Browse files
Added DFS (Recursive) - Graph (TheAlgorithms#228)
1 parent 4534582 commit b5899d5

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎Graphs/DepthFirstSearchRecursive.js‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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+
DFSRecursive (node, value, visited = new Set()) {
21+
// DFS Function to search if a node with the given value is present in the graph
22+
// checking if the searching node has been found
23+
if (node === value) { return true }
24+
// adding the current node to the visited set
25+
visited.add(node)
26+
// calling the helper function recursivly for all unvisited nodes
27+
for (const neighbour of this.connections[node]) {
28+
if (!visited.has(neighbour)) {
29+
if (this.DFSRecursive(neighbour, value, visited)) { return true }
30+
}
31+
}
32+
return false
33+
}
34+
}
35+
36+
function main () {
37+
const graph = new GraphUnweightedUndirected()
38+
graph.addEdge(1, 2)
39+
graph.addEdge(2, 3)
40+
graph.addEdge(2, 4)
41+
graph.addEdge(3, 5)
42+
console.log(graph.DFSRecursive(5, 1))
43+
console.log(graph.DFSRecursive(5, 100))
44+
}
45+
46+
main()

0 commit comments

Comments
(0)

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