Skip to content

Commit b8b037d

Browse files
committed
algo(BFS): implementation with python
1 parent 920e0c4 commit b8b037d

File tree

1 file changed

+121
-0
lines changed
  • src/algorithm_practice/Graph_Algorithms

1 file changed

+121
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
from collections import deque
2+
from random import choice, randint
3+
4+
node_names = ["admiring",
5+
"adoring",
6+
"affectionate",
7+
"agitated",
8+
"amazing",
9+
"angry",
10+
"awesome",
11+
"backstabbing",
12+
"berserk",
13+
"big",
14+
"boring",
15+
"clever",
16+
"cocky",
17+
"compassionate",
18+
"condescending",
19+
"cranky",
20+
"desperate",
21+
"determined",
22+
"distracted",
23+
"dreamy",
24+
"drunk",
25+
"eager",
26+
"ecstatic",
27+
"elastic",
28+
"elated",
29+
"elegant",
30+
"evil",
31+
"fervent",
32+
"focused",
33+
"furious",
34+
"gigantic",
35+
"gloomy",
36+
"goofy",
37+
"grave",
38+
"happy",
39+
"high",
40+
"hopeful",
41+
"hungry",
42+
"infallible",
43+
"jolly",
44+
"jovial",
45+
"kickass",
46+
"lonely",
47+
"loving",
48+
"mad",
49+
"modest",
50+
"naughty",
51+
"nauseous",
52+
"nostalgic",
53+
"peaceful",
54+
"pedantic",
55+
"pensive",
56+
"prickly",
57+
"reverent",
58+
"romantic",
59+
"sad",
60+
"serene",
61+
"sharp",
62+
"sick",
63+
"silly",
64+
"sleepy",
65+
"small",
66+
"stoic",
67+
"stupefied",
68+
"suspicious",
69+
"tender",
70+
"thirsty",
71+
"tiny",
72+
"trusting",
73+
"zen"]
74+
75+
def node(nid):
76+
name = choice(node_names) + "-" + str(randint(1000,9999))
77+
return {"name": name, "id": nid, "adj": set()}
78+
79+
80+
def generate_graph(nodes):
81+
graph = []
82+
for n in range(0, nodes):
83+
n = node(n)
84+
for i in range(randint(0, 5)):
85+
n['adj'].add(randint(0, nodes-1))
86+
graph.append(n)
87+
return graph
88+
89+
g = generate_graph(50)
90+
91+
92+
def bfs(graph, root_n):
93+
k = []
94+
for i in range(0, len(graph)):
95+
k.append({"distance": None, "parent": None})
96+
97+
root = graph[root_n]
98+
Q = deque()
99+
k[root_n]['distance'] = 0
100+
Q.append(root)
101+
102+
while len(Q) > 0:
103+
current = Q.pop()
104+
for adjecent_node_n in current['adj']:
105+
if not k[adjecent_node_n]['distance']:
106+
k[adjecent_node_n]['distance'] = k[current['id']]['distance'] + 1
107+
k[adjecent_node_n]['parent'] = current['id']
108+
Q.append(graph[adjecent_node_n])
109+
return k
110+
111+
112+
def print_distances(graph, tree):
113+
for n, i in enumerate(tree):
114+
name = graph[n]['name']
115+
print(n, name, "with distance of", i['distance'], "from root, its parent is", i['parent'])
116+
117+
118+
if __name__=="__main__":
119+
# start
120+
print_distances(g, bfs(g, 0))
121+
pass

0 commit comments

Comments
 (0)