Skip to content

Commit 7386f90

Browse files
committed
Python code for depth first search. rev1.
1 parent dafe8ae commit 7386f90

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

DepthFirstSearch.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
class Vertex:
2+
def __init__(self, n):
3+
self.name = n
4+
self.neighbors = list()
5+
6+
self.discovery = 0
7+
self.finish = 0
8+
self.color = 'black'
9+
10+
def add_neighbor(self, v):
11+
nset = set(self.neighbors)
12+
if v not in nset:
13+
self.neighbors.append(v)
14+
self.neighbors.sort()
15+
16+
class Graph:
17+
vertices = {}
18+
time = 0
19+
20+
def add_vertex(self, vertex):
21+
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
22+
self.vertices[vertex.name] = vertex
23+
return True
24+
else:
25+
return False
26+
27+
def add_edge(self, u, v):
28+
if u in self.vertices and v in self.vertices:
29+
for key, value in self.vertices.items():
30+
if key == u:
31+
value.add_neighbor(v)
32+
if key == v:
33+
value.add_neighbor(u)
34+
return True
35+
else:
36+
return False
37+
38+
def print_graph(self):
39+
for key in sorted(list(self.vertices.keys())):
40+
print(key + str(self.vertices[key].neighbors) + " " + str(self.vertices[key].discovery) + "/" + str(self.vertices[key].finish))
41+
42+
def _dfs(self, vertex):
43+
global time
44+
vertex.color = 'red'
45+
vertex.discovery = time
46+
time += 1
47+
for v in vertex.neighbors:
48+
if self.vertices[v].color == 'black':
49+
self._dfs(self.vertices[v])
50+
vertex.color = 'blue'
51+
vertex.finish = time
52+
time += 1
53+
54+
def dfs(self, vertex):
55+
global time
56+
time = 1
57+
self._dfs(vertex)
58+
59+
g = Graph()
60+
# print(str(len(g.vertices)))
61+
a = Vertex('A')
62+
g.add_vertex(a)
63+
g.add_vertex(Vertex('B'))
64+
for i in range(ord('A'), ord('K')):
65+
g.add_vertex(Vertex(chr(i)))
66+
67+
edges = ['AB', 'AE', 'BF', 'CG', 'DE', 'DH', 'EH', 'FG', 'FI', 'FJ', 'GJ', 'HI']
68+
for edge in edges:
69+
g.add_edge(edge[:1], edge[1:])
70+
71+
g.dfs(a)
72+
g.print_graph()

0 commit comments

Comments
 (0)