Design and Analysis of Algorithms Lab - 4
Design and Analysis of Algorithms Lab - 4
(BCSE204P)
Faculty: - Dr Malini S
AIM:
ALGORITHM:
Step 1: Preprocessing
for i from 0 to n - m:
if textHash == patternHash:
if text[i:i+m] == pattern:
return i
if i < n - m:
textHash = recomputeHash(text, i, i+m, textHash)
function hash(string):
// Compute hash value of string using a suitable hashing function
• Typing
• onetwoTyping
OUTPUT/RESULT:
Example2:
VERIFICATION STATUS
Q2.) Bellman-Ford
AIM
The Bellman-Ford algorithm is used to find the shortest paths from a single
source vertex to all other vertices in a weighted graph, even in the presence
of negative weight edges, provided that there are no negative cycles. Its
primary aim is to handle graphs with negative edge weights, which Dijkstra's
algorithm cannot handle efficiently.
ALGORITHM
• Initialization:
1.) Initialize an array dist to store the shortest distances from the source
vertex to all other vertices. Set the distance to the source vertex as 0 and
all other distances as infinity.
2.) Initialize an array prev to keep track of the predecessor vertices on the
shortest paths.
• Relaxation:
1.) Repeat the relaxation process for V-1 iterations, where V is the number
of vertices in the graph.
2.) For each edge (u, v) in the graph, relax the edge by updating the shortest
distance to vertex v if the distance to vertex u plus the weight of edge (u,
v) is smaller than the current shortest distance to v.
3.) Update the prev array to record the predecessor vertex for each vertex
with a relaxed edge.
1.) After V-1 iterations, if there are still vertices whose distances can be
reduced, then a negative weight cycle exists in the graph.
2.) Iterate through all edges and relax each edge once more.
3.) If any distance is updated during this iteration, it indicates the presence
of a negative cycle.
PSEUDOCODE:
// Step 2: Relaxation
for i from 1 to |V(G)| - 1:
for each edge (u, v) in G:
if dist[u] + weight(u, v) < dist[v]:
dist[v] = dist[u] + weight(u, v)
prev[v] = u
AIM
Floyd-Warshall algorithm aims to find the shortest paths between all pairs of
vertices in a weighted graph, including negative weight edges (but with no
negative cycles). It achieves this by iteratively updating shortest path
estimates between pairs of vertices until reaching the optimal solution.
ALGORITHM
Step 1: Initialization
• Create a matrix dist to store the shortest distances between all pairs
of vertices.
• Initialize the matrix such that dist[i][j] represents the shortest
distance from vertex i to vertex j.
• If there's an edge from vertex i to vertex j, set dist[i][j] to the
weight of that edge. If there's no edge, set dist[i][j] to infinity.
• Initialize the diagonal elements of the matrix to 0.
Step 4: Output
• After completing the main algorithm, the dist matrix will contain
the shortest distances between all pairs of vertices.
PSEUDOCODE:
return dist
C/C++ CODE:
OUTPUT:
VERIFICATION STATUS