-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathGraph_BFS&DFS.py
73 lines (64 loc) · 1.82 KB
/
Graph_BFS&DFS.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Vertex:
def __init__(self, key, adjacent):
self.key = key
self.adjacent = adjacent
class Graph:
def __init__(self):
self.node = {}
def AddVertex(self, key, adjance=[], rank=[]):
A = []
if rank == []:
rank = [1 for i in range(0, len(adjance))]
for i in range(0, len(adjance)):
A.append((self.node[adjance[i]], rank[i]))
self.node[key] = Vertex(key, A)
def AddEdge(self, u, v, r):
for i in self.node[u].adjacent:
if i[0].key == v:
return False
self.node[u].adjacent.append((self.node[v], r))
def BDFS(self, s, t):
OPEN = []
CLOSE = []
OPEN.append(self.node[s])
self.Recursion(OPEN, CLOSE, t)
return CLOSE
def Recursion(self, OPEN, CLOSE, s):
if len(OPEN) == 0:
return
i = OPEN.pop(0)
CLOSE.append(i)
for j in i.adjacent:
isUndiscover = True
for k in OPEN:
if j[0] == k:
isUndiscover = False
for k in CLOSE:
if j[0] == k:
isUndiscover = False
if (isUndiscover):
if s == "BFS":
OPEN.append(j[0])
elif s == "DFS":
OPEN.insert(0, j[0])
self.Recursion(OPEN, CLOSE,s)
G = Graph()
G.AddVertex("H")
G.AddVertex("I")
G.AddVertex("J")
G.AddVertex("K")
G.AddVertex("L")
G.AddVertex("M")
G.AddVertex("N")
G.AddVertex("O")
G.AddVertex("D", ["H", "I"])
G.AddVertex("E", ["J", "K"])
G.AddVertex("F", ["L", "M"])
G.AddVertex("G", ["N", "O"])
G.AddVertex("B", ["D", "E"])
G.AddVertex("C", ["F", "G"])
G.AddVertex("A", ["B", "C"])
LIST = G.BDFS("A", "BFS")
print [i.key for i in LIST]
LIST = G.BDFS("A", "DFS")
print [i.key for i in LIST]