-
Notifications
You must be signed in to change notification settings - Fork 0
/
depth_first_search.rb
50 lines (45 loc) · 1.4 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
# Depth-first search (DFS) is an algorithm for traversing or
# searching a tree, tree structure, or graph. One starts at
# the root (selecting some node as the root in the graph case)
# and explores as far as possible along each branch before backtracking.
#
# A graph can be represented by its adjacency matrix G,
# where G[i][j] == 1 if there is an edge between
# vertices i and j and 0 otherwise.
#
# Below Graph in diagram http://i.imgur.com/sV1UzUn.png
G = [0,1,1,0,0,1,1], # A
[1,0,0,0,0,0,0],
[1,0,0,0,0,0,0],
[0,0,0,0,1,1,0],
[0,0,0,1,0,1,1],
[1,0,0,1,1,0,0],
[1,0,0,0,1,0,0] # G
LABLES = %w(A B C D E F G)
def dfs(vertex)
# mark v as explored
print "#{LABLES[vertex]} " # visited
# nullify the row to mark the
# vertex as visited
edge = 0
while edge < G.size
G[vertex][edge] = 0
edge += 1
end
# Find unexplored edges
edge = 0
while edge < G.size
# not explored and not same vertex
if ( G[edge][vertex] != 0 && edge != vertex)
dfs(edge)
end
edge += 1
end
end
p dfs(0) # Replace 0 with 1..6 to see different paths
p dfs(1) # Replace 0 with 1..6 to see different paths
p dfs(2) # Replace 0 with 1..6 to see different paths
p dfs(3) # Replace 0 with 1..6 to see different paths
p dfs(4) # Replace 0 with 1..6 to see different paths
p dfs(5) # Replace 0 with 1..6 to see different paths
p dfs(6) # Replace 0 with 1..6 to see different paths