Skip to content

Commit 8e6db7a

Browse files
authored
Merge pull request #173 from py-ranoid/patch-1
Added basic-graphs.py with common graph algorithms
2 parents 535cbb7 + 0dcf27f commit 8e6db7a

File tree

1 file changed

+267
-0
lines changed

1 file changed

+267
-0
lines changed

Diff for: Graphs/basic-graphs.py

+267
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
1+
# Accept No. of Nodes and edges
2+
n, m = map(int, raw_input().split(" "))
3+
4+
# Initialising Dictionary of edges
5+
g = {}
6+
for i in xrange(n):
7+
g[i + 1] = []
8+
9+
"""
10+
--------------------------------------------------------------------------------
11+
Accepting edges of Unweighted Directed Graphs
12+
--------------------------------------------------------------------------------
13+
"""
14+
for _ in xrange(m):
15+
x, y = map(int, raw_input().split(" "))
16+
g[x].append(y)
17+
18+
"""
19+
--------------------------------------------------------------------------------
20+
Accepting edges of Unweighted Undirected Graphs
21+
--------------------------------------------------------------------------------
22+
"""
23+
for _ in xrange(m):
24+
x, y = map(int, raw_input().split(" "))
25+
g[x].append(y)
26+
g[y].append(x)
27+
28+
"""
29+
--------------------------------------------------------------------------------
30+
Accepting edges of Weighted Undirected Graphs
31+
--------------------------------------------------------------------------------
32+
"""
33+
for _ in xrange(m):
34+
x, y, r = map(int, raw_input().split(" "))
35+
g[x].append([y, r])
36+
g[y].append([x, r])
37+
38+
"""
39+
--------------------------------------------------------------------------------
40+
Depth First Search.
41+
Args : G - Dictionary of edges
42+
s - Starting Node
43+
Vars : vis - Set of visited nodes
44+
S - Traversal Stack
45+
--------------------------------------------------------------------------------
46+
"""
47+
48+
49+
def dfs(G, s):
50+
vis, S = set([s]), [s]
51+
print s
52+
while S:
53+
flag = 0
54+
for i in G[S[-1]]:
55+
if i not in vis:
56+
S.append(i)
57+
vis.add(i)
58+
flag = 1
59+
print i
60+
break
61+
if not flag:
62+
S.pop()
63+
64+
65+
"""
66+
--------------------------------------------------------------------------------
67+
Breadth First Search.
68+
Args : G - Dictionary of edges
69+
s - Starting Node
70+
Vars : vis - Set of visited nodes
71+
Q - Traveral Stack
72+
--------------------------------------------------------------------------------
73+
"""
74+
from collections import deque
75+
76+
77+
def bfs(G, s):
78+
vis, Q = set([s]), deque([s])
79+
print s
80+
while Q:
81+
u = Q.popleft()
82+
for v in G[u]:
83+
if v not in vis:
84+
vis.add(v)
85+
Q.append(v)
86+
print v
87+
88+
89+
"""
90+
--------------------------------------------------------------------------------
91+
Dijkstra's shortest path Algorithm
92+
Args : G - Dictionary of edges
93+
s - Starting Node
94+
Vars : dist - Dictionary storing shortest distance from s to every other node
95+
known - Set of knows nodes
96+
path - Preceding node in path
97+
--------------------------------------------------------------------------------
98+
"""
99+
100+
101+
def dijk(G, s):
102+
dist, known, path = {s: 0}, set(), {s: 0}
103+
while True:
104+
if len(known) == len(G) - 1:
105+
break
106+
mini = 100000
107+
for i in dist:
108+
if i not in known and dist[i] < mini:
109+
mini = dist[i]
110+
u = i
111+
known.add(u)
112+
for v in G[u]:
113+
if v[0] not in known:
114+
if dist[u] + v[1] < dist.get(v[0], 100000):
115+
dist[v[0]] = dist[u] + v[1]
116+
path[v[0]] = u
117+
for i in dist:
118+
if i != s:
119+
print dist[i]
120+
121+
122+
"""
123+
--------------------------------------------------------------------------------
124+
Topological Sort
125+
--------------------------------------------------------------------------------
126+
"""
127+
from collections import deque
128+
129+
130+
def topo(G, ind=None, Q=[1]):
131+
if ind == None:
132+
ind = [0] * (len(G) + 1) # SInce oth Index is ignored
133+
for u in G:
134+
for v in G[u]:
135+
ind[v] += 1
136+
Q = deque()
137+
for i in G:
138+
if ind[i] == 0:
139+
Q.append(i)
140+
if len(Q) == 0:
141+
return
142+
v = Q.popleft()
143+
print v
144+
for w in G[v]:
145+
ind[w] -= 1
146+
if ind[w] == 0:
147+
Q.append(w)
148+
topo(G, ind, Q)
149+
150+
151+
"""
152+
--------------------------------------------------------------------------------
153+
Reading an Adjacency matrix
154+
--------------------------------------------------------------------------------
155+
"""
156+
157+
158+
def adjm():
159+
n, a = input(), []
160+
for i in xrange(n):
161+
a.append(map(int, raw_input().split()))
162+
return a, n
163+
164+
165+
"""
166+
--------------------------------------------------------------------------------
167+
Floyd Warshall's algorithm
168+
Args : G - Dictionary of edges
169+
s - Starting Node
170+
Vars : dist - Dictionary storing shortest distance from s to every other node
171+
known - Set of knows nodes
172+
path - Preceding node in path
173+
174+
--------------------------------------------------------------------------------
175+
"""
176+
177+
178+
def floy((A, n)):
179+
dist = list(A)
180+
path = [[0] * n for i in xrange(n)]
181+
for k in xrange(n):
182+
for i in xrange(n):
183+
for j in xrange(n):
184+
if dist[i][j] > dist[i][k] + dist[k][j]:
185+
dist[i][j] = dist[i][k] + dist[k][j]
186+
path[i][k] = k
187+
print dist
188+
189+
190+
"""
191+
--------------------------------------------------------------------------------
192+
Prim's MST Algorithm
193+
Args : G - Dictionary of edges
194+
s - Starting Node
195+
Vars : dist - Dictionary storing shortest distance from s to nearest node
196+
known - Set of knows nodes
197+
path - Preceding node in path
198+
--------------------------------------------------------------------------------
199+
"""
200+
201+
202+
def prim(G, s):
203+
dist, known, path = {s: 0}, set(), {s: 0}
204+
while True:
205+
if len(known) == len(G) - 1:
206+
break
207+
mini = 100000
208+
for i in dist:
209+
if i not in known and dist[i] < mini:
210+
mini = dist[i]
211+
u = i
212+
known.add(u)
213+
for v in G[u]:
214+
if v[0] not in known:
215+
if v[1] < dist.get(v[0], 100000):
216+
dist[v[0]] = v[1]
217+
path[v[0]] = u
218+
219+
220+
"""
221+
--------------------------------------------------------------------------------
222+
Accepting Edge list
223+
Vars : n - Number of nodes
224+
m - Number of edges
225+
Returns : l - Edge list
226+
n - Number of Nodes
227+
--------------------------------------------------------------------------------
228+
"""
229+
230+
231+
def edglist():
232+
n, m = map(int, raw_input().split(" "))
233+
l = []
234+
for i in xrange(m):
235+
l.append(map(int, raw_input().split(' ')))
236+
return l, n
237+
238+
239+
"""
240+
--------------------------------------------------------------------------------
241+
Kruskal's MST Algorithm
242+
Args : E - Edge list
243+
n - Number of Nodes
244+
Vars : s - Set of all nodes as unique disjoint sets (initially)
245+
--------------------------------------------------------------------------------
246+
"""
247+
248+
249+
def krusk((E, n)):
250+
# Sort edges on the basis of distance
251+
E.sort(reverse=True, key=lambda x: x[2])
252+
s = [set([i]) for i in range(1, n + 1)]
253+
while True:
254+
if len(s) == 1:
255+
break
256+
print s
257+
x = E.pop()
258+
for i in xrange(len(s)):
259+
if x[0] in s[i]:
260+
break
261+
for j in xrange(len(s)):
262+
if x[1] in s[j]:
263+
if i == j:
264+
break
265+
s[j].update(s[i])
266+
s.pop(i)
267+
break

0 commit comments

Comments
 (0)