0% found this document useful (0 votes)
3 views22 pages

Unit - IV

The document covers various algorithms related to trees and graphs, including tree traversals, BFS, DFS, Dijkstra's Shortest Path, Bellman-Ford, and Floyd's algorithms. Each algorithm is explained with Python code examples demonstrating their implementation and outputs. It highlights the use cases and differences between the algorithms, particularly in handling weighted graphs and negative edge weights.

Uploaded by

22pa1a05g2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Unit - IV

The document covers various algorithms related to trees and graphs, including tree traversals, BFS, DFS, Dijkstra's Shortest Path, Bellman-Ford, and Floyd's algorithms. Each algorithm is explained with Python code examples demonstrating their implementation and outputs. It highlights the use cases and differences between the algorithms, particularly in handling weighted graphs and negative edge weights.

Uploaded by

22pa1a05g2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

COMPETITIVE

CODING
EMPLOYABILITY SKILLS – I

G. Amulya,
Assistant Professor
Unit - IV
Trees and Graphs
 Tree Traversals
 BFS
 DFS
 Dijkstra's Shortest Path algorithm
 Bell-man Ford Algorithm
 Floyd's algorithm
Tree Traversals (Inorder)
class TreeNode:
def __init__(self, val):
self.val = val root = TreeNode(1)
self.left = None root.left = TreeNode(2)
self.right = None root.right = TreeNode(3)
def inorderTraversal(root): root.left.left = TreeNode(4)
answer = [] root.left.right = TreeNode(5)
inorderTraversalUtil(root, answer) print(inorderTraversal(root))
return answer
def inorderTraversalUtil(root, answer): Output:
if root is None: [4, 2, 5, 1, 3]
return
inorderTraversalUtil(root.left, answer)
answer.append(root.val)
inorderTraversalUtil(root.right, answer)
return
BFS

Breadth-First Search (BFS)


is an algorithm used for
traversing graphs or trees.
Traversing means visiting
each node of the graph.
graph = {
'5' : ['3','7'], Output:
'3' : ['2', '4'],
'7' : ['8'], '2' : [ ],
5 3 7 2 4 8
'4' : ['8'], '8' : [ ]
}
visited = [], queue = []
def bfs(visited, graph, node):
visited.append(node) v=[5]
queue.append(node) q=[5]
while queue:
m = queue.pop(0) m=5 m=3 m=7 m=2 m=4
q=[ ] q=[7] q=[2,4] q=[4,8] q=[8]
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour) v=[5,3,7] v=[5,3,7,2,4] v=[5,3,7,2,4,8] v=[5,3,7,2,4,8] q=[8]
queue.append(neighbour) q=[3,7] q=[7,2,4] q=[2,4,8] q=[4,8]
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')
DFS
● Before learning the python
code for Depth-First and its
output, let us go through the
algorithm it follows for the
same.
● The recursive method of the
Depth-First Search algorithm is
implemented using stack.
● A standard Depth-First Search
implementation puts every
vertex of the graph into one in
all 2 categories: 1) Visited 2)
Not Visited.
graph = {
'5' : ['3','7'], Output:
'3' : ['2', '4'], Following is the Depth-First Search
'7' : ['8'], 5 3 2 4 8 7
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set() v=()
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node) v = (5) v = (5,3) v = (5,3,2) v = (5,3,2,4)
for neighbour in graph[node]: n = 3, 7 n = 2,4,7 n = 4,7 n = 8,7
dfs(visited, graph, neighbour)
print("Following is the Depth-First v= v = (5,3,2,4,8,7)
Search") (5,3,2,4,8)
n=7 n = empty
dfs(visited, graph, '5')
Dijkstra’s Shortest Path Algorithm
Dijkstra’s algorithm is used to find the shortest path between two points in a
weighted graph. It is essential for solving problems such as network routing
and mapping.
Python Program
import heapq
from numpy import Inf

graph = {
0: [ (1, 1) ],
1: [ (0, 1), (2, 2), (3, 3) ],
2: [ (1, 2), (3, 1), (4, 5) ],
3: [ (1, 3), (2, 1), (4, 1) ],
4: [ (2, 5), (3, 1) ]
}

print ( Dijkstra ( graph, 0 ) )


def Dijkstra(graph, start):
5 0
n = len(graph)
dist = [Inf for i in range(n)] dist=[Inf, Inf, Inf, Inf, Inf]
dist[start] = 0 dist=[0, Inf, Inf, Inf, Inf]
vis = [False for i in range(n)] vis=[F, F, F, F, F]
pqueue = [(0, start)] pqueue=[(0,0)]

while len(pqueue) > 0:


i, u = heapq.heappop(pqueue) i=0, u=0
if vis[u]:
continue
vis[u] = True vis[0]=T vis=[ T, F, F, F, F ]
for v, d in graph[u]:
dist = [ 0, 1, Inf, Inf, Inf ]
if dist[u] + d < dist[v]:
dist[v] = dist[u] + d
heapq.heappush(pqueue, (dist[v], v))
return dist
vis=[ T, F, F, F, F ]
1: [ (0, 1), (2, 2), (3, 3) ]
dist = [ 0, 1, Inf, Inf, Inf ]
1

while len(pqueue) > 0:


i, u = heapq.heappop(pqueue) i=1, u=1
if vis[u]:
vis[1]
continue
vis[u] = True vis=[ T, T, F, F, F ]
for v, d in graph[u]:
if dist[u] + d < dist[v]: dist = [ 0, 1, 3, 4, Inf ]
dist[v] = dist[u] + d
heapq.heappush(pqueue, (dist[v], v))
return dist
vis=[ T, T, F, F, F ]
2: [ (1, 2), (3, 1), (4, 5) ] dist = [ 0, 1, 3, 4, Inf ]
2

while len(pqueue) > 0:


i, u = heapq.heappop(pqueue) i=2, u=2
if vis[u]:
vis[2]
continue
vis[u] = True vis=[ T, T, T, F, F ]
for v, d in graph[u]:
if dist[u] + d < dist[v]: dist = [ 0, 1, 3, 4, 8 ]
dist[v] = dist[u] + d
heapq.heappush(pqueue, (dist[v], v))
return dist
vis=[ T, T, T, F, F ]
3: [ (1, 3), (2, 1), (4, 1) ] dist = [ 0, 1, 3, 4, 8 ]

while len(pqueue) > 0:


i, u = heapq.heappop(pqueue) i=3, u=3 3
if vis[u]:
vis[3]
continue
vis[u] = True vis=[ T, T, T, T, F ]
for v, d in graph[u]:
if dist[u] + d < dist[v]: dist = [ 0, 1, 3, 4, 5 ]
dist[v] = dist[u] + d
heapq.heappush(pqueue, (dist[v], v))
return dist
vis=[ T, T, T, T, F ]
4: [ (2, 5), (3, 1) ]
dist = [ 0, 1, 3, 4, 5 ]

while len(pqueue) > 0:


i, u = heapq.heappop(pqueue) i=4, u=4 4
if vis[u]:
vis[4]
continue
vis[u] = True vis=[ T, T, T, T, T ] Output:
for v, d in graph[u]:
if dist[u] + d < dist[v]: dist = [ 0, 1, 3, 4, 5 ]
[ 0, 1, 3, 4, 5]
dist[v] = dist[u] + d
heapq.heappush(pqueue, (dist[v], v))
return dist
Bell-man Ford Algorithm

● A Bellman-Ford algorithm is
also guaranteed to find the
shortest path in a graph, similar
to Dijkstra’s algorithm.

● Although Bellman-Ford is
slower than Dijkstra’s algorithm,
it is capable of handling graphs
with negative edge weights,
which makes it more versatile.
from numpy import Inf
graph = {
0: [(1, 1)],
1: [(0, 1), (2, 2), (3, 3)],
2: [(1, 2), (3, 1), (4, 5)],
3: [(1, 3), (2, 1), (4, 1)],
4: [(2, -2), (3, 1)]
}

start_node=0
result = BellmanFord(graph, start_node)

if result == "Negative-weight cycle detected":


print("Negative-weight cycle detected in the graph.")
else:
print("Shortest distances from node", start_node, "to all other nodes:")
for node, dist in enumerate(result):
print(f"Node {node}: {dist}")
def BellmanFord(graph, start):
num_nodes = len(graph)
distance = [Inf for i in range(num_nodes)]
distance[start] = 0

for i in range(num_nodes):
for u in range(num_nodes):
for v, weight in graph[u]:
if distance[u] + weight < distance[v]:
distance[v] = distance[u] + weight

# Check for negative-weight cycles


for u in range(num_nodes):
for v, weight in graph[u]:
if distance[u] + weight < distance[v]:
return "Negative-weight cycle detected"

return distance
Floyd’s Algorithm

The Floyd Warshall Algorithm is for solving all pairs of shortest-path problems.
The problem is to find the shortest distances between every pair of vertices in a
given edge-weighted directed Graph. It is an algorithm for finding the shortest
path between all the pairs of vertices in a weighted graph.
nV = 4,INF = 999

G = [[0, 3, INF, 5],


[2, 0, INF, 4],
[INF, 1, 0, INF],
[INF, INF, 2, 0]]
floyd_warshall(G)
def floyd_warshall(G):
distance = list(map(lambda i: list(map(lambda j: j, i)), G))

# Adding vertices individually


for k in range(nV):
for i in range(nV):
for j in range(nV):
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
print_solution(distance)
# Printing the solution
def print_solution(distance): G = [ [0, 3, 7, 5],
for i in range(nV): [2, 0, 6, 4],
for j in range(nV): [3, 1, 0, 5],
if(distance[i][j] == INF): [5, 3, 2, 0] ]
print("INF", end=" ")
else:
print(distance[i][j], end=" ")
print(" ")

You might also like