0% found this document useful (0 votes)
19 views11 pages

21bce2321 Daa Da4

dfgh

Uploaded by

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

21bce2321 Daa Da4

dfgh

Uploaded by

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

DAA Assignment-3

Name-Rahul jain
Reg No.-21BCE2321

Algorithm: Bellman-Ford Algorithm


Purpose:
The Bellman-Ford algorithm computes the shortest path from a single source vertex to all other
vertices in a weighted graph. It works even with graphs that have negative weight edges and
can detect negative weight cycles.

Steps:

1. Initialize Distances:
○ Set the distance of the source vertex to 0.
○ Set the distance of all other vertices to infinity (a very large number).
○ This ensures that the source vertex is prioritized during pathfinding.
2. Relax All Edges (|V| - 1) Times:
○ For each vertex in the graph, you repeat the edge relaxation process.
○ Relaxation involves checking each edge in the graph and updating the distance
to the destination vertex if a shorter path is found through the source vertex.
○ This is repeated |V| - 1 times because the longest possible path without a cycle in
a graph with V vertices has at most (V - 1) edges.
3. Check for Negative-Weight Cycles:
○ After relaxing all edges |V| - 1 times, the shortest path to each vertex should be
finalized.
○ To detect any negative-weight cycles, check all edges one more time.
○ If you can still relax any edge, it means that a negative-weight cycle exists in the
graph. The algorithm should report the presence of such a cycle.
4. Return Shortest Paths or Report Negative Cycle:
○ If no negative-weight cycle is detected, the algorithm will output the shortest path
from the source to all vertices.
○ If a negative cycle is detected, output that a negative-weight cycle exists.

Time Complexity:

● The Bellman-Ford algorithm runs in O(V * E) time, where:


○ V = Number of vertices
○ E = Number of edges
● The reason for this time complexity is that for each vertex, you process every edge,
which leads to a complexity of O(V * E).
Code
import java.util.Arrays;

class BellmanFord {
class Edge {
int source, destination, weight;
Edge() {
source = destination = weight = 0;
}
}

int V, E;
Edge edge[];

BellmanFord(int v, int e) {
V = v;
E = e;
edge = new Edge[e];
for (int i = 0; i < e; ++i)
edge[i] = new Edge();
}

void BellmanFordAlgorithm(BellmanFord graph, int src) {


int V = graph.V, E = graph.E;
int dist[] = new int[V];

// Step 1: Initialize distances from source to all other vertices as INFINITE


Arrays.fill(dist, Integer.MAX_VALUE);
dist[src] = 0;

// Step 2: Relax all edges |V| - 1 times


for (int i = 1; i < V; ++i) {
for (int j = 0; j < E; ++j) {
int u = graph.edge[j].source;
int v = graph.edge[j].destination;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v])
dist[v] = dist[u] + weight;
}
}

// Step 3: Check for negative-weight cycles


for (int j = 0; j < E; ++j) {
int u = graph.edge[j].source;
int v = graph.edge[j].destination;
int weight = graph.edge[j].weight;
if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) {
System.out.println("Graph contains negative weight cycle");
return;
}
}

// Print the calculated shortest distances


printArr(dist, V);
}

// A utility function to print the constructed distance array


void printArr(int dist[], int V) {
System.out.println("Vertex Distance from Source");
for (int i = 0; i < V; ++i)
System.out.println(i + "\t\t" + dist[i]);
}

public static void main(String[] args) {


int V = 5; // Number of vertices in the graph
int E = 8; // Number of edges in the graph

BellmanFord graph = new BellmanFord(V, E);

// Adding edges as per the diagram


graph.edge[0].source = 0;
graph.edge[0].destination = 1;
graph.edge[0].weight = -1;

graph.edge[1].source = 0;
graph.edge[1].destination = 2;
graph.edge[1].weight = 4;

graph.edge[2].source = 1;
graph.edge[2].destination = 2;
graph.edge[2].weight = 3;

graph.edge[3].source = 1;
graph.edge[3].destination = 3;
graph.edge[3].weight = 2;

graph.edge[4].source = 1;
graph.edge[4].destination = 4;
graph.edge[4].weight = 2;

graph.edge[5].source = 3;
graph.edge[5].destination = 2;
graph.edge[5].weight = 5;

graph.edge[6].source = 3;
graph.edge[6].destination = 1;
graph.edge[6].weight = 1;

graph.edge[7].source = 4;
graph.edge[7].destination = 3;
graph.edge[7].weight = -3;

int src = 0;
graph.BellmanFordAlgorithm(graph, src);
}
}

Output
Algorithm: Floyd-Warshall Algorithm
Purpose:
The Floyd-Warshall algorithm is used to find the shortest paths between all pairs of vertices in a
weighted graph. This algorithm works even with negative weights, but the graph should not
have negative weight cycles.

Steps of the Floyd-Warshall Algorithm:

1. Initialization:
○ Create a 2D matrix dist[][], where each element dist[i][j] represents the shortest
distance from vertex i to vertex j.
○ Initially, the matrix is filled with direct distances between the vertices. If there is
no direct edge between two vertices, the distance is initialized to infinity.
2. Iterative Update:
○ The algorithm runs through each vertex k as an intermediate point between two
vertices i and j.
○ For each pair of vertices (i, j), the algorithm checks if the path through vertex k
offers a shorter route than the previously known shortest path and updates the
matrix if necessary.
○ This is done for all vertices in the graph.
3. Negative Cycles:
○ If the diagonal of the matrix dist[i][i] ends up negative for any vertex i, then a
negative weight cycle exists, as a vertex can reach itself through a cycle with a
negative total weight.
4. Final Matrix:
○ After running the algorithm, the matrix dist[i][j] will contain the shortest distances
between every pair of vertices.

Time Complexity:

● The time complexity of the Floyd-Warshall algorithm is O(V³), where V is the number of
vertices.
○ This is because there are three nested loops that iterate over all vertices.
Code
import java.util.Arrays;

public class FloydWarshall {


final static int INF = 99999, V = 5;

// Function to implement the Floyd-Warshall algorithm


void floydWarshall(int graph[][]) {
int dist[][] = new int[V][V];

// Initialize the solution matrix with input graph matrix


for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
dist[i][j] = graph[i][j];

// Add all vertices one by one to the set of intermediate vertices


for (int k = 0; k < V; k++) {
// Pick all vertices as source one by one
for (int i = 0; i < V; i++) {
// Pick all vertices as destination for the above picked source
for (int j = 0; j < V; j++) {
// If vertex k is on the shortest path from i to j, then update dist[i][j]
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}

// Print the shortest distance matrix


printSolution(dist);
}

// Function to print the shortest distance matrix


void printSolution(int dist[][]) {
System.out.println("The following matrix shows the shortest distances between every pair
of vertices:");
for (int i = 0; i < V; ++i) {
for (int j = 0; j < V; ++j) {
if (dist[i][j] == INF)
System.out.print("INF ");
else
System.out.print(dist[i][j] + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


/* Let us create the following weighted graph represented by a 2D array
A B C D E
A [0, 2, INF, INF, 1]
B [INF, 0, 6, INF, INF]
C [INF, INF, 0, 1, INF]
D [INF, INF, INF, 0, 3]
E [4, INF, 7, INF, 0]
*/
int graph[][] = {
{0, 2, INF, INF, 1},
{INF, 0, 6, INF, INF},
{INF, INF, 0, 1, INF},
{INF, INF, INF, 0, 3},
{4, INF, 7, INF, 0}
};

FloydWarshall fw = new FloydWarshall();


fw.floydWarshall(graph);
}
}

Output
Algorithm: Ford-Fulkerson Algorithm
Purpose:
The Ford-Fulkerson algorithm computes the maximum flow in a flow network. The idea is to find
valid augmenting paths in the residual graph and add flow along those paths until no more
augmenting paths can be found.

Steps of the Ford-Fulkerson Algorithm:

1. Initialization:
○ Start with an initial flow of 0.
○ The residual graph initially equals the original capacity graph.
2. Find Augmenting Paths:
○ While there exists an augmenting path from the source (S) to the sink (T) in the
residual graph, increase the flow.
○ An augmenting path is a path where we can push more flow (i.e., the path has
available capacity).
3. Update Residual Graph:
○ For each augmenting path found, update the flow along the path by adding the
flow to the forward edges and subtracting it from the backward edges (residual
capacity).
○ This is done to ensure that the flow conservation property holds at each vertex.
4. Terminate When No More Augmenting Paths:
○ The algorithm terminates when no more augmenting paths can be found in the
residual graph.
○ The total flow is the sum of the flows along the augmenting paths found during
the algorithm.

Time Complexity:

● O(max_flow * E), where E is the number of edges and max_flow is the maximum
possible flow in the network.
○ In each iteration, the algorithm looks for an augmenting path and adjusts the flow,
which can take O(E) time.
○ In the worst case, if we increase the flow by just 1 unit each time, we could need
O(max_flow) iterations.
Code
import java.util.LinkedList;

public class FordFulkerson {


static final int V = 8; // Number of vertices in the graph

/* Returns true if there is a path from source 's' to sink 't' in the residual graph.
Also fills parent[] to store the path. */
boolean bfs(int rGraph[][], int s, int t, int parent[]) {
// Create a visited array and mark all vertices as not visited
boolean visited[] = new boolean[V];
for (int i = 0; i < V; ++i)
visited[i] = false;

// Create a queue, enqueue source vertex and mark it as visited


LinkedList<Integer> queue = new LinkedList<Integer>();
queue.add(s);
visited[s] = true;
parent[s] = -1;

// Standard BFS Loop


while (queue.size() != 0) {
int u = queue.poll();

for (int v = 0; v < V; v++) {


if (!visited[v] && rGraph[u][v] > 0) {
// If we find a connection to the sink, then return true
if (v == t) {
parent[v] = u;
return true;
}
queue.add(v);
parent[v] = u;
visited[v] = true;
}
}
}
return false; // No augmenting path found
}

// Returns the maximum flow from s to t in the given graph


int fordFulkerson(int graph[][], int s, int t) {
int u, v;
// Create a residual graph and fill the residual graph with given capacities in the original
graph
int rGraph[][] = new int[V][V];
for (u = 0; u < V; u++)
for (v = 0; v < V; v++)
rGraph[u][v] = graph[u][v];

// This array is filled by BFS and stores the path


int parent[] = new int[V];

int maxFlow = 0; // There is no flow initially

// Augment the flow while there is a path from source to sink


while (bfs(rGraph, s, t, parent)) {
// Find the maximum flow through the path found by BFS
int pathFlow = Integer.MAX_VALUE;
for (v = t; v != s; v = parent[v]) {
u = parent[v];
pathFlow = Math.min(pathFlow, rGraph[u][v]);
}

// Update the residual capacities of the edges and reverse edges along the path
for (v = t; v != s; v = parent[v]) {
u = parent[v];
rGraph[u][v] -= pathFlow;
rGraph[v][u] += pathFlow;
}

// Add the path flow to the overall flow


maxFlow += pathFlow;
}

return maxFlow;
}

public static void main(String[] args) {


// Create a graph based on the provided example
int graph[][] = new int[][]{
{0, 6, 10, 0, 0, 0, 0, 0}, // S
{0, 0, 2, 4, 0, 0, 0, 0}, // A
{0, 0, 0, 0, 9, 4, 0, 0}, // B
{0, 0, 0, 0, 6, 0, 10, 0}, // D
{0, 0, 0, 0, 0, 6, 0, 10}, // E
{0, 0, 0, 0, 0, 0, 0, 5}, // F
{0, 0, 0, 0, 0, 0, 0, 12}, // G
{0, 0, 0, 0, 0, 0, 0, 0} // T
};
FordFulkerson ff = new FordFulkerson();

System.out.println("The maximum possible flow is " + ff.fordFulkerson(graph, 0, 7));


}
}

Output

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy