-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS.py
76 lines (64 loc) · 1.87 KB
/
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
74
75
76
import random as r
class Node:
def __init__(self,value):
self.value = value
self.neighbors = []
self.explored = False
def is_explored(self):
return self.explored
def explore(self):
self.explored = True
def add_neighbor(self, node):
self.neighbors.append(node)
def get_neighbors(self):
return self.neighbors
def is_neighbor(self, node):
isneighbor = False
for i in self.neighbors:
if i == node:
isneighbor = True
break
return isneighbor
def get_value(self):
return self.value
def is_not_neighbor(self, node):
return not self.is_neighbor(node)
def display(self):
print(self.value,':',end = ' ')
for i in self.neighbors:
print(i.get_value(),end=',')
print()
def generate_random_graph(n):
addedlist = []
for i in range(0,n):
node = Node(i)
if len(addedlist) != 0:
randnode = r.choice(addedlist)
node.add_neighbor(randnode)
randnode.add_neighbor(node)
for j in range(0,len(addedlist)):
if (r.randint(0,10) < 3) and (node.is_not_neighbor(addedlist[j])):
node.add_neighbor(addedlist[j])
addedlist[j].add_neighbor(node)
addedlist.append(node)
return addedlist
def loop_bfs():
node = stack.pop()
print(node.get_value(),end=',')
neighbors = node.get_neighbors()
for k in neighbors:
if not k.is_explored():
stack.append(k)
k.explore()
if len(stack) == 0:
return
loop_bfs()
return
nodelist = generate_random_graph(6)
for i in nodelist:
i.display()
stack = []
rnode = r.choice(nodelist)
rnode.explore()
stack.append(rnode)
loop_bfs()