Skip to content

Commit

Permalink
Merge pull request #831 from Prabhatsingh001/main
Browse files Browse the repository at this point in the history
added three algorithms in DSA folder
  • Loading branch information
UTSAVS26 authored Oct 25, 2024
2 parents 331cbb0 + 5a1cb91 commit 905cff9
Show file tree
Hide file tree
Showing 3 changed files with 256 additions and 0 deletions.
56 changes: 56 additions & 0 deletions Algorithms_and_Data_Structures/bellman_ford/Bellman_ford.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
def BellmanFord(src, V, graph):
'''
this algorithm works exactly like dijkistra algorthm except it
can detect negative edge cycle in the graph
this algo is little slower than dijkistra algortihm
'''
#src is source vertex V is no of vertex graph is graph in the form of a list of list
dist = [float("Inf")]*V
dist[src] = 0

for _ in range(V-1):
for u,v,w in graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
dist[v] = dist[u] + w


for u,v,w in graph:
if dist[u] != float("Inf") and dist[u] + w < dist[v]:
return -1

return dist

def printArr(dist):
V = len(dist)
print("vertex distance from source")
for i in range(V):
print(f"{i}\t\t{dist[i]}")

#example usage of bellman ford algorithm
def main():
v = 5
graph = []
graph.append([0,1,-1]) #[u=initial vertex, final vertex, w = weight of edge btw them]
graph.append([0,2,4])
graph.append([1,2,3])
graph.append([1,3,2])
graph.append([1,4,2])
graph.append([3,2,5])
graph.append([3,1,1])
graph.append([4,3,-3])

dist = BellmanFord(0,v,graph)
printArr(dist)

if __name__ == "__main__":
main()

'''output
vertex distance from source
0 0
1 -1
2 2
3 -2
4 1
'''
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import math

class Point:
def __init__(self, x, y):
self.x = x
self.y = y

#sort array of points according to X coordinate
def compareX(a, b):
p1, p2 = a, b
return (p1.x != p2.x) * (p1.x - p2.x) + (p1.y - p2.y)

#sort array of points according to Y coordinate
def compareY(a, b):
p1, p2 = a, b
return (p1.y != p2.y) * (p1.y - p2.y) + (p1.x - p2.x)


# A utility function to find the distance between two points
def dist(p1, p2):
return math.sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2)

'''A Brute Force method to return the smallest distance between two points
in P[] of size n'''
def bruteForce(P, n):
min = float('inf')
for i in range(n):
for j in range(i+1, n):
if dist(P[i], P[j]) < min:
min = dist(P[i], P[j])
return min

# A utility function to find a minimum of two float values
def min(x, y):
return x if x < y else y

'''# A utility function to find the distance between the closest points of strip of a given size. All points in strip[] are sorted according to
y coordinate. They all have an upper bound on minimum distance as d.Note that this method seems to be a O(n^2) method, but it's a O(n) method as the inner loop runs at most 6 times'''
def stripClosest(strip, size, d):
min = d
for i in range(size):
for j in range(i+1, size):
if (strip[j].y - strip[i].y) < min:
if dist(strip[i],strip[j]) < min:
min = dist(strip[i], strip[j])

return min

'''A recursive function to find the smallest distance.
The array Px contains all points sorted according to x coordinates and Py contains all points sorted according to y coordinates'''
def closestUtil(Px, Py, n):
if n <= 3:
return bruteForce(Px, n)

mid = n // 2
midPoint = Px[mid]

Pyl = [None] * mid
Pyr = [None] * (n-mid)
li = ri = 0
for i in range(n):
if ((Py[i].x < midPoint.x or (Py[i].x == midPoint.x and Py[i].y < midPoint.y)) and li<mid):
Pyl[li] = Py[i]
li += 1
else:
Pyr[ri] = Py[i]
ri += 1

dl = closestUtil(Px, Pyl, mid)
dr = closestUtil(Px[mid:], Pyr, n-mid)

d = min(dl, dr)
strip = [None] * n
j = 0
for i in range(n):
if abs(Py[i].x - midPoint.x) < d:
strip[j] = Py[i]
j += 1
return stripClosest(strip, j, d)


def closest(P, n):
Px = P
Py = P
Px.sort(key=lambda x:x.x)
Py.sort(key=lambda x:x.y)

return closestUtil(Px, Py, n)

#example usage
if __name__ == '__main__':
P = [Point(2, 3), Point(12, 30), Point(40, 50), Point(5, 1), Point(12, 10), Point(3, 4)]
n = len(P)
print("The smallest distance is", closest(P, n))

'''output
The smallest distance is 1.4142135623730951
'''
102 changes: 102 additions & 0 deletions Algorithms_and_Data_Structures/graham_scan/convex_hull_graham_scan.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
from functools import cmp_to_key

class Point:
def __init__(self,x=None,y=None):
self.x = x
self.y = y

p0 = Point(0,0)

def nextToTop(s):
return s[-2]

def distSq(p1,p2):
return ((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y))

'''
To find orientation of ordered triplet (p, q, r).
The function returns following values
0 --> p, q and r are collinear
1 --> Clockwise
2 --> Counterclockwise
'''

def orientation(p,q,r):
val = ((q.y - p.y)*(r.x - q.x) - (q.x - p.x)*(r.y-q.y))

if val == 0:
return 0
elif val > 0:
return 1
else:
return 2

def compare(p1,p2):
'''
function that checks orientation
'''

o = orientation(p0,p1,p2)
if o == 0:
if distSq(p0,p2) >= distSq(p0,p1):
return -1
else:
return 1
else:
if o == 2:
return -1
else:
return 1

def convexHull(points,n):
ymin = points[0].y
min = 0
for i in range(1,n):
y = points[i].y

if((y<min) or (ymin == y and points[i].x < points[min].x)):
ymin = points[i].y
min = i

points[0],points[min] = points[min],points[0]

p0 = points[0]
points = sorted(points,key=cmp_to_key(compare))

m = 1
for i in range(1,n):

while((i<n-1) and (orientation(p0,points[i],points[i+1])==0)):
i += 1

points[m] = points[i]
m+=1

if m < 3:
return

S = []
S.append(points[0])
S.append(points[1])
S.append(points[2])

for i in range(3, m):

while ((len(S) > 1) and
(orientation(nextToTop(S), S[-1], points[i]) != 2)):
S.pop()
S.append(points[i])

while S:
p = S[-1]
print("(" + str(p.x) + ", " + str(p.y) + ")")
S.pop()


#example usage
input_points = [(0, 3), (1, 1), (2, 2), (4, 4),(0, 0), (1, 2), (3, 1), (3, 3)]
points = []
for point in input_points:
points.append(Point(point[0], point[1]))
n = len(points)
convexHull(points, n)

0 comments on commit 905cff9

Please sign in to comment.