-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathDFS_PATH.py
57 lines (46 loc) · 1.53 KB
/
DFS_PATH.py
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
from BuildGraphFromFile import BuildGraphFromFile
from SparseGraph import SparseGraph
from DenseGraph import DenseGraph
class dfs:
def __init__(self, graph, s):
self.graph = graph
self.visited = [0] * self.graph.V()
self.path = [-1] * self.graph.V()
self.s = s
# print(self.graph, self.visited)
self._dfs(s)
self.path[s] = -1
def _dfs(self, index):
self.visited[index] = 1
for w in self.graph[index]:
if not self.visited[w]:
self.path[w] = index
self._dfs(w)
def hasPath(self, w):
return self.visited[w] == 1
def pathFrom(self, w):
if not self.hasPath(w):
return []
else:
a = []
while self.path[w] != -1:
a.append(w)
w = self.path[w]
a.append(0)
return list(reversed(a))
def showPath(self, w):
return "->".join(list(map(lambda ele:str(ele),self.pathFrom(w))))
if __name__ == "__main__":
g1 = SparseGraph(13) # 必须填入正确的结点个数。。。我真的觉得邻接矩阵不好用
BuildGraphFromFile(g1, 'testG2.txt')
df = dfs(g1, 0)
print(df.showPath(6))
# for elem in g1[0]:
# print(elem)
# print("-----")
# g2 = DenseGraph(13) # 必须填入正确的结点个数。。。我真的觉得邻接矩阵不好用
# BuildGraphFromFile(g2, 'testG1.txt')
# for elem in g2[0]:
# print(elem)
# df = dfs(g2)
# print(df._ccount())