mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-07-26 01:43:17 +08:00
Added Dequeue in Python
This commit is contained in:
101
Graphs/a_star.py
Normal file
101
Graphs/a_star.py
Normal file
@ -0,0 +1,101 @@
|
||||
|
||||
grid = [[0, 1, 0, 0, 0, 0],
|
||||
[0, 1, 0, 0, 0, 0],#0 are free path whereas 1's are obstacles
|
||||
[0, 1, 0, 0, 0, 0],
|
||||
[0, 1, 0, 0, 1, 0],
|
||||
[0, 0, 0, 0, 1, 0]]
|
||||
|
||||
'''
|
||||
heuristic = [[9, 8, 7, 6, 5, 4],
|
||||
[8, 7, 6, 5, 4, 3],
|
||||
[7, 6, 5, 4, 3, 2],
|
||||
[6, 5, 4, 3, 2, 1],
|
||||
[5, 4, 3, 2, 1, 0]]'''
|
||||
|
||||
init = [0, 0]
|
||||
goal = [len(grid)-1, len(grid[0])-1] #all coordinates are given in format [y,x]
|
||||
cost = 1
|
||||
|
||||
#the cost map which pushes the path closer to the goal
|
||||
heuristic = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
|
||||
for i in range(len(grid)):
|
||||
for j in range(len(grid[0])):
|
||||
heuristic[i][j] = abs(i - goal[0]) + abs(j - goal[1])
|
||||
if grid[i][j] == 1:
|
||||
heuristic[i][j] = 99 #added extra penalty in the heuristic map
|
||||
|
||||
|
||||
#the actions we can take
|
||||
delta = [[-1, 0 ], # go up
|
||||
[ 0, -1], # go left
|
||||
[ 1, 0 ], # go down
|
||||
[ 0, 1 ]] # go right
|
||||
|
||||
|
||||
#function to search the path
|
||||
def search(grid,init,goal,cost,heuristic):
|
||||
|
||||
closed = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]# the referrence grid
|
||||
closed[init[0]][init[1]] = 1
|
||||
action = [[0 for col in range(len(grid[0]))] for row in range(len(grid))]#the action grid
|
||||
|
||||
x = init[0]
|
||||
y = init[1]
|
||||
g = 0
|
||||
f = g + heuristic[init[0]][init[0]]
|
||||
cell = [[f, g, x, y]]
|
||||
|
||||
found = False # flag that is set when search is complete
|
||||
resign = False # flag set if we can't find expand
|
||||
|
||||
while not found and not resign:
|
||||
if len(cell) == 0:
|
||||
resign = True
|
||||
return "FAIL"
|
||||
else:
|
||||
cell.sort()#to choose the least costliest action so as to move closer to the goal
|
||||
cell.reverse()
|
||||
next = cell.pop()
|
||||
x = next[2]
|
||||
y = next[3]
|
||||
g = next[1]
|
||||
f = next[0]
|
||||
|
||||
|
||||
if x == goal[0] and y == goal[1]:
|
||||
found = True
|
||||
else:
|
||||
for i in range(len(delta)):#to try out different valid actions
|
||||
x2 = x + delta[i][0]
|
||||
y2 = y + delta[i][1]
|
||||
if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):
|
||||
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
|
||||
g2 = g + cost
|
||||
f2 = g2 + heuristic[x2][y2]
|
||||
cell.append([f2, g2, x2, y2])
|
||||
closed[x2][y2] = 1
|
||||
action[x2][y2] = i
|
||||
invpath = []
|
||||
x = goal[0]
|
||||
y = goal[1]
|
||||
invpath.append([x, y])#we get the reverse path from here
|
||||
while x != init[0] or y != init[1]:
|
||||
x2 = x - delta[action[x][y]][0]
|
||||
y2 = y - delta[action[x][y]][1]
|
||||
x = x2
|
||||
y = y2
|
||||
invpath.append([x, y])
|
||||
|
||||
path = []
|
||||
for i in range(len(invpath)):
|
||||
path.append(invpath[len(invpath) - 1 - i])
|
||||
print "ACTION MAP"
|
||||
for i in range(len(action)):
|
||||
print action[i]
|
||||
|
||||
return path
|
||||
|
||||
a = search(grid,init,goal,cost,heuristic)
|
||||
for i in range(len(a)):
|
||||
print a[i]
|
||||
|
267
Graphs/basic-graphs.py
Normal file
267
Graphs/basic-graphs.py
Normal file
@ -0,0 +1,267 @@
|
||||
# Accept No. of Nodes and edges
|
||||
n, m = map(int, raw_input().split(" "))
|
||||
|
||||
# Initialising Dictionary of edges
|
||||
g = {}
|
||||
for i in xrange(n):
|
||||
g[i + 1] = []
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Accepting edges of Unweighted Directed Graphs
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
for _ in xrange(m):
|
||||
x, y = map(int, raw_input().split(" "))
|
||||
g[x].append(y)
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Accepting edges of Unweighted Undirected Graphs
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
for _ in xrange(m):
|
||||
x, y = map(int, raw_input().split(" "))
|
||||
g[x].append(y)
|
||||
g[y].append(x)
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Accepting edges of Weighted Undirected Graphs
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
for _ in xrange(m):
|
||||
x, y, r = map(int, raw_input().split(" "))
|
||||
g[x].append([y, r])
|
||||
g[y].append([x, r])
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Depth First Search.
|
||||
Args : G - Dictionary of edges
|
||||
s - Starting Node
|
||||
Vars : vis - Set of visited nodes
|
||||
S - Traversal Stack
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
|
||||
|
||||
def dfs(G, s):
|
||||
vis, S = set([s]), [s]
|
||||
print s
|
||||
while S:
|
||||
flag = 0
|
||||
for i in G[S[-1]]:
|
||||
if i not in vis:
|
||||
S.append(i)
|
||||
vis.add(i)
|
||||
flag = 1
|
||||
print i
|
||||
break
|
||||
if not flag:
|
||||
S.pop()
|
||||
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Breadth First Search.
|
||||
Args : G - Dictionary of edges
|
||||
s - Starting Node
|
||||
Vars : vis - Set of visited nodes
|
||||
Q - Traveral Stack
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
from collections import deque
|
||||
|
||||
|
||||
def bfs(G, s):
|
||||
vis, Q = set([s]), deque([s])
|
||||
print s
|
||||
while Q:
|
||||
u = Q.popleft()
|
||||
for v in G[u]:
|
||||
if v not in vis:
|
||||
vis.add(v)
|
||||
Q.append(v)
|
||||
print v
|
||||
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Dijkstra's shortest path Algorithm
|
||||
Args : G - Dictionary of edges
|
||||
s - Starting Node
|
||||
Vars : dist - Dictionary storing shortest distance from s to every other node
|
||||
known - Set of knows nodes
|
||||
path - Preceding node in path
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
|
||||
|
||||
def dijk(G, s):
|
||||
dist, known, path = {s: 0}, set(), {s: 0}
|
||||
while True:
|
||||
if len(known) == len(G) - 1:
|
||||
break
|
||||
mini = 100000
|
||||
for i in dist:
|
||||
if i not in known and dist[i] < mini:
|
||||
mini = dist[i]
|
||||
u = i
|
||||
known.add(u)
|
||||
for v in G[u]:
|
||||
if v[0] not in known:
|
||||
if dist[u] + v[1] < dist.get(v[0], 100000):
|
||||
dist[v[0]] = dist[u] + v[1]
|
||||
path[v[0]] = u
|
||||
for i in dist:
|
||||
if i != s:
|
||||
print dist[i]
|
||||
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Topological Sort
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
from collections import deque
|
||||
|
||||
|
||||
def topo(G, ind=None, Q=[1]):
|
||||
if ind == None:
|
||||
ind = [0] * (len(G) + 1) # SInce oth Index is ignored
|
||||
for u in G:
|
||||
for v in G[u]:
|
||||
ind[v] += 1
|
||||
Q = deque()
|
||||
for i in G:
|
||||
if ind[i] == 0:
|
||||
Q.append(i)
|
||||
if len(Q) == 0:
|
||||
return
|
||||
v = Q.popleft()
|
||||
print v
|
||||
for w in G[v]:
|
||||
ind[w] -= 1
|
||||
if ind[w] == 0:
|
||||
Q.append(w)
|
||||
topo(G, ind, Q)
|
||||
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Reading an Adjacency matrix
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
|
||||
|
||||
def adjm():
|
||||
n, a = input(), []
|
||||
for i in xrange(n):
|
||||
a.append(map(int, raw_input().split()))
|
||||
return a, n
|
||||
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Floyd Warshall's algorithm
|
||||
Args : G - Dictionary of edges
|
||||
s - Starting Node
|
||||
Vars : dist - Dictionary storing shortest distance from s to every other node
|
||||
known - Set of knows nodes
|
||||
path - Preceding node in path
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
|
||||
|
||||
def floy((A, n)):
|
||||
dist = list(A)
|
||||
path = [[0] * n for i in xrange(n)]
|
||||
for k in xrange(n):
|
||||
for i in xrange(n):
|
||||
for j in xrange(n):
|
||||
if dist[i][j] > dist[i][k] + dist[k][j]:
|
||||
dist[i][j] = dist[i][k] + dist[k][j]
|
||||
path[i][k] = k
|
||||
print dist
|
||||
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Prim's MST Algorithm
|
||||
Args : G - Dictionary of edges
|
||||
s - Starting Node
|
||||
Vars : dist - Dictionary storing shortest distance from s to nearest node
|
||||
known - Set of knows nodes
|
||||
path - Preceding node in path
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
|
||||
|
||||
def prim(G, s):
|
||||
dist, known, path = {s: 0}, set(), {s: 0}
|
||||
while True:
|
||||
if len(known) == len(G) - 1:
|
||||
break
|
||||
mini = 100000
|
||||
for i in dist:
|
||||
if i not in known and dist[i] < mini:
|
||||
mini = dist[i]
|
||||
u = i
|
||||
known.add(u)
|
||||
for v in G[u]:
|
||||
if v[0] not in known:
|
||||
if v[1] < dist.get(v[0], 100000):
|
||||
dist[v[0]] = v[1]
|
||||
path[v[0]] = u
|
||||
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Accepting Edge list
|
||||
Vars : n - Number of nodes
|
||||
m - Number of edges
|
||||
Returns : l - Edge list
|
||||
n - Number of Nodes
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
|
||||
|
||||
def edglist():
|
||||
n, m = map(int, raw_input().split(" "))
|
||||
l = []
|
||||
for i in xrange(m):
|
||||
l.append(map(int, raw_input().split(' ')))
|
||||
return l, n
|
||||
|
||||
|
||||
"""
|
||||
--------------------------------------------------------------------------------
|
||||
Kruskal's MST Algorithm
|
||||
Args : E - Edge list
|
||||
n - Number of Nodes
|
||||
Vars : s - Set of all nodes as unique disjoint sets (initially)
|
||||
--------------------------------------------------------------------------------
|
||||
"""
|
||||
|
||||
|
||||
def krusk((E, n)):
|
||||
# Sort edges on the basis of distance
|
||||
E.sort(reverse=True, key=lambda x: x[2])
|
||||
s = [set([i]) for i in range(1, n + 1)]
|
||||
while True:
|
||||
if len(s) == 1:
|
||||
break
|
||||
print s
|
||||
x = E.pop()
|
||||
for i in xrange(len(s)):
|
||||
if x[0] in s[i]:
|
||||
break
|
||||
for j in xrange(len(s)):
|
||||
if x[1] in s[j]:
|
||||
if i == j:
|
||||
break
|
||||
s[j].update(s[i])
|
||||
s.pop(i)
|
||||
break
|
Reference in New Issue
Block a user