Skip to content

Commit 823ce64

Browse files
authored
Merge pull request #1 from TheAlgorithms/master
Update Branch
2 parents f9156cf + bb3287a commit 823ce64

File tree

81 files changed

+3984
-478
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

81 files changed

+3984
-478
lines changed

Diff for: Graphs/a_star.py

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
2+
grid = [[0, 1, 0, 0, 0, 0],
3+
[0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles
4+
[0, 1, 0, 0, 0, 0],
5+
[0, 1, 0, 0, 1, 0],
6+
[0, 0, 0, 0, 1, 0]]
7+
8+
'''
9+
heuristic = [[9, 8, 7, 6, 5, 4],
10+
[8, 7, 6, 5, 4, 3],
11+
[7, 6, 5, 4, 3, 2],
12+
[6, 5, 4, 3, 2, 1],
13+
[5, 4, 3, 2, 1, 0]]'''
14+
15+
init = [0, 0]
16+
goal = [len(grid)-1, len(grid[0])-1] #all coordinates are given in format [y,x]
17+
cost = 1
18+
19+
#the cost map which pushes the path closer to the goal
20+
heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
21+
for i in range(len(grid)):
22+
for j in range(len(grid[0])):
23+
heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])
24+
if grid[i][j] == 1:
25+
heuristic[i][j] = 99 #added extra penalty in the heuristic map
26+
27+
28+
#the actions we can take
29+
delta = [[-1, 0 ], # go up
30+
[ 0, -1], # go left
31+
[ 1, 0 ], # go down
32+
[ 0, 1 ]] # go right
33+
34+
35+
#function to search the path
36+
def search(grid,init,goal,cost,heuristic):
37+
38+
closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]# the referrence grid
39+
closed[init[0]][init[1]] = 1
40+
action = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]#the action grid
41+
42+
x = init[0]
43+
y = init[1]
44+
g = 0
45+
f = g + heuristic[init[0]][init[0]]
46+
cell = [[f, g, x, y]]
47+
48+
found = False # flag that is set when search is complete
49+
resign = False # flag set if we can't find expand
50+
51+
while not found and not resign:
52+
if len(cell) == 0:
53+
resign = True
54+
return "FAIL"
55+
else:
56+
cell.sort()#to choose the least costliest action so as to move closer to the goal
57+
cell.reverse()
58+
next = cell.pop()
59+
x = next[2]
60+
y = next[3]
61+
g = next[1]
62+
f = next[0]
63+
64+
65+
if x == goal[0] and y == goal[1]:
66+
found = True
67+
else:
68+
for i in range(len(delta)):#to try out different valid actions
69+
x2 = x + delta[i][0]
70+
y2 = y + delta[i][1]
71+
if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):
72+
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
73+
g2 = g + cost
74+
f2 = g2 + heuristic[x2][y2]
75+
cell.append([f2, g2, x2, y2])
76+
closed[x2][y2] = 1
77+
action[x2][y2] = i
78+
invpath = []
79+
x = goal[0]
80+
y = goal[1]
81+
invpath.append([x, y])#we get the reverse path from here
82+
while x != init[0] or y != init[1]:
83+
x2 = x - delta[action[x][y]][0]
84+
y2 = y - delta[action[x][y]][1]
85+
x = x2
86+
y = y2
87+
invpath.append([x, y])
88+
89+
path = []
90+
for i in range(len(invpath)):
91+
path.append(invpath[len(invpath) - 1 - i])
92+
print "ACTION MAP"
93+
for i in range(len(action)):
94+
print action[i]
95+
96+
return path
97+
98+
a = search(grid,init,goal,cost,heuristic)
99+
for i in range(len(a)):
100+
print a[i]
101+

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)