forked from LeslieK/Algorithms-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepthFirstPaths.py
More file actions
35 lines (28 loc) · 756 Bytes
/
DepthFirstPaths.py
File metadata and controls
35 lines (28 loc) · 756 Bytes
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
class DepthFirstSearch(object):
"depth first search graph processing class"
def __init__(self, G, source):
self.marked = [ False for i in range(G.V()) ]
self.edgeTo = [NaN for i in range(G.V()) ]
self.dfs(G, source)
def dfs(self, Graph, v):
"""
process graph using depth-first search
create marked[] and edgeTo[] data structures
"""
self.marked[v] = True
for w in Graph.adj(v):
if (not self.marked[w]):
self.dfs(Graph, w)
self.edgeTo[w] = v
def hasPathTo(self, v):
"True if source hasPathTo a vertex v"
return self.marked[v]
def pathTo(self, v):
if not self.hasPath(v): return None
i = v
path = []
while i != source:
path.append(i)
i = self.edgeTo[i]
path.append(source)
return path.reverse()