Uh oh!
There was an error while loading. Please reload this page.
forked from joeyajames/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDepthFirstSearch.py
More file actions
Latest commit
71 lines (60 loc) · 1.56 KB
/
Copy pathDepthFirstSearch.py
File metadata and controls
71 lines (60 loc) · 1.56 KB
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
classVertex:
def__init__(self, n):
self.name=n
self.neighbors=list()
self.discovery=0
self.finish=0
self.color='black'
defadd_neighbor(self, v):
ifvnotinself.neighbors:
self.neighbors.append(v)
self.neighbors.sort()
classGraph:
vertices= {}
time=0
defadd_vertex(self, vertex):
ifisinstance(vertex, Vertex) andvertex.namenotinself.vertices:
self.vertices[vertex.name] =vertex
returnTrue
else:
returnFalse
defadd_edge(self, u, v):
ifuinself.verticesandvinself.vertices:
forkey, valueinself.vertices.items():
ifkey==u:
value.add_neighbor(v)
ifkey==v:
value.add_neighbor(u)
returnTrue
else:
returnFalse
defprint_graph(self):
forkeyinsorted(list(self.vertices.keys())):
print(key+str(self.vertices[key].neighbors) +" "+str(self.vertices[key].discovery) +"/"+str(self.vertices[key].finish))
def_dfs(self, vertex):
globaltime
vertex.color='red'
vertex.discovery=time
time+=1
forvinvertex.neighbors:
ifself.vertices[v].color=='black':
self._dfs(self.vertices[v])
vertex.color='blue'
vertex.finish=time
time+=1
defdfs(self, vertex):
globaltime
time=1
self._dfs(vertex)
g=Graph()
# print(str(len(g.vertices)))
a=Vertex('A')
g.add_vertex(a)
g.add_vertex(Vertex('B'))
foriinrange(ord('A'), ord('K')):
g.add_vertex(Vertex(chr(i)))
edges= ['AB', 'AE', 'BF', 'CG', 'DE', 'DH', 'EH', 'FG', 'FI', 'FJ', 'GJ', 'HI']
foredgeinedges:
g.add_edge(edge[:1], edge[1:])
g.dfs(a)
g.print_graph()