-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdfs.rb
53 lines (44 loc) · 942 Bytes
/
dfs.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
require 'set'
# Depth-first search to find paths in an undirected graph.
# The graph is represented as an adjacency list of Integers,
# see examples in test/dfs_test.rb
class DFS
class Graph
attr_accessor :size, :adj
def initialize(size)
@size = size
@adj = Array.new(size) { Set.new }
end
def add_edge(v, w)
@adj[v].add(w)
@adj[w].add(v)
end
end
def initialize(graph, source)
@graph = graph
@source = source
@edge_to = Array.new(graph.size, nil)
@visited = Array.new(graph.size, false)
search(source)
end
def path_to(v)
return nil unless @visited[v]
path = []
w = v
while w != @source
path.push(w)
w = @edge_to[w]
end
path.push(@source)
path.reverse
end
private
def search(v)
@visited[v] = true
@graph.adj[v].each do |w|
next if @visited[w]
@edge_to[w] = v
search(w)
end
end
end