forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Depth_First_Search.rb
91 lines (74 loc) · 2.03 KB
/
Depth_First_Search.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class Graph
attr_accessor :num_verticies
# Constructor to initialise graph
def initialize(num_verticies)
@num_verticies = num_verticies
@adj_list = Array.new(num_verticies) {|i| Array.new}
end
# method for adding edges to graph
def add_edge(source, destination)
@adj_list[source].push(destination)
end
# depth first search
def dfs(start)
# initialization array for marking visited vertices
used_verticies = Array.new(num_verticies, false)
# calling recursive DFS from 'start' vertex
private_dfs(start, used_verticies)
end
private
# recursive DFS
def private_dfs(vertex, used_verticies)
print vertex, ' '
used_verticies[vertex] = true
# going to adjacent vetrices if they are not visited
@adj_list[vertex].each { |adj_vertex|
if used_verticies[adj_vertex] == false
then private_dfs(adj_vertex, used_verticies)
end
}
end
end
def test1
# create a graph with 8 verticies
graph = Graph.new(8)
# Create edges vetween verticies
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 2)
graph.add_edge(1, 4)
graph.add_edge(2, 0)
graph.add_edge(2, 3)
graph.add_edge(3, 3)
graph.add_edge(3, 6)
graph.add_edge(4, 0)
graph.add_edge(4, 5)
graph.add_edge(5, 6)
graph.add_edge(5, 7)
graph.add_edge(6, 2)
graph.add_edge(7, 3)
print "Depth First traversal is: "
graph.dfs(0)
puts ""
# Expected Output
# Depth First Traversal is: 0 1 2 3 6 4 5 7
end
def test2
# create a graph with 7 verticies
graph = Graph.new(7)
# Create edges vetween verticies
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(2, 5)
graph.add_edge(2, 6)
print "Depth First traversal is: "
graph.dfs(0)
puts ""
# Expected Output
# Depth First Traversal is: 0 1 3 4 2 5 6
end
#testing the program
test1()
test2()