0% found this document useful (0 votes)
4 views58 pages

Unit 3 Graph.pptx

This document provides an overview of graphs, including their definitions, types, and key terminology such as vertices and edges. It details various graph representations, traversal methods (Depth-First Search and Breadth-First Search), and their respective algorithms and properties. Additionally, it discusses applications of graph algorithms and methods for detecting cycles in both undirected and directed graphs.

Uploaded by

soluraai
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)
4 views58 pages

Unit 3 Graph.pptx

This document provides an overview of graphs, including their definitions, types, and key terminology such as vertices and edges. It details various graph representations, traversal methods (Depth-First Search and Breadth-First Search), and their respective algorithms and properties. Additionally, it discusses applications of graph algorithms and methods for detecting cycles in both undirected and directed graphs.

Uploaded by

soluraai
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/ 58

Unit 3 Graph

Prepared By: Ms. Shraddha Patel


Graph
• A graph is a mathematical structure that represents relationships between objects by connecting a set of
points.
• It is used to establish a pairwise relationship between elements in a given set.
• Graphs are widely used in discrete mathematics, computer science and network theory to represent
relationships between objects.
• Graph consists of vertices (nodes) connected by edges (lines).
• Graph G is represented as:
G = (V, E)
• V is the set of vertices (nodes).
• E is the set of edges (connections) between pairs of vertices.
Types of Graph
1. Finite - Infinite
2. Trivial - Null
3. Simple - Regular
4. Multi - Pseudo
5. Complete
6. Directed – Undirected
7. Weighted – Unweighted
8. Sparse – Dense
9. Connected – Disconnected
10. Cyclic - Acyclic
Finite – Infinite Graph
• A graph is said to be finite if it has a finite number of vertices and a finite number of edges.

• A graph is called an infinite graph if it has an infinite number of vertices and an infinite number of edges
Trivial – Null Graph
• A graph G= (V, E) is trivial if it contains only a single vertex and no edges.

• It's a reworked version of a trivial graph. If several vertices but no edges connect them, a graph G= (V, E) is a
null graph.
Multi – Pseudo Graph
• If there are parallel edges between a pair of vertices in a graph G= (V, E), the graph is referred to as a
multigraph.
• There are no self-loops in a Multigraph.

• If a graph G= (V, E) contains a self-loop besides other edges, it is a pseudo graph.


Simple – Regular Graph
• If each pair of nodes or vertices in a graph G=(V, E) has only one edge, it is a simple graph.
• As a result, there is just one edge linking two vertices, depicting one-to-one interactions between two
elements.

• If a graph G= (V, E) is a simple graph with the same degree at each vertex, it is a regular graph.
Complete or Full Graph
• If a graph G= (V, E) is also a simple graph, it is complete.
• Using the edges, with n number of vertices must be connected.
• It's also known as a full graph because each vertex's degree must be n-1 where n is number of vertices.
• A complete graph has n(n–1)/2 edges, where n is the number of nodes in G.
Weighted – Unweighted Graph
• A graph G= (V, E) is called a labelled or weighted graph because each edge has a value or weight
representing the cost of traversing that edge.
Directed – Undirected Graph
• A directed graph also referred to as a digraph, is a set of nodes connected by edges, each with a direction.

• The order of the two connected vertices is irrelevant and has no direction.
Sparse – Dense Graph
• A sparse graph with relatively few edges compared to the number of vertices.
• A dense graph with many edges compared to the number of vertices.

Fig. Sparse Graph Fig. Dense Graph


Connected – Disconnected Graph
• If there is a path between one vertex to any other vertex, the graph is connected.

• When there is no edge linking the vertices, you refer to the null graph as a disconnected graph.
Cyclic – Acyclic Graph
• If a graph contains at least one graph cycle, it is considered to be cyclic.
• When there are no cycles in a graph, it is called an acyclic graph.

Fig. Acyclic Graph


Fig. Cyclic Graph
Graph Terminology
Term Definition Example

Vertex (Node) A fundamental part of a graph representing an object or point. In a social network graph, each person is a vertex.

Edge (Link) A connection between two vertices in a graph. In a social network graph, a friendship between two people is an edge.

Degree The number of edges connected to a vertex. In a social network, if a person has three friends, their degree is 3.

In-Degree The number of incoming edges to a vertex in a directed graph. In a Twitter network, the number of followers a person has.

Out-Degree The number of outgoing edges from a vertex in a directed graph. In a Twitter network, the number of people a person follows.

In a city map graph, a path represents the route from one city to another
Path A sequence of vertices connected by edges.
through connecting roads.

In a road network, traveling from city A to B to C and back to A forms a


Cycle A path that starts and ends at the same vertex without repeating any edges or vertices.
cycle.

In a computer network, two computers directly connected by a cable are


Adjacency Two vertices are adjacent if they are connected by an edge.
adjacent.
Graph Representation Methods
• A Graph representation tells us how a Graph is stored in memory.
• Graph representations store information about which vertices are adjacent and how the edges between the
vertices are.
• Graph representations are different if the edges are directed or weighted.
• There are two ways for graph representation:
1. Adjacency Matrix
2. Adjacency List
Adjacency Matrix Graph Representation
• The Adjacency Matrix is a 2D array (matrix) where each cell on index (i, j) stores information about the edge from vertex
i to vertex j.

• The adjacency matrix above represents an undirected graph, so the values '1' only tells us where the edges are.
• Also, the values in the adjacency matrix is symmetrical because the edges go in both ways (undirected Graph).
Contd…
• To create a directed graph with an adjacency matrix, we must decide which vertices the edges go from and to, by
inserting the value at the correct indexes (i,j).

• In the adjacency matrix above, the value 3 on index (0,1) tells us there is an edge from vertex A to vertex B and the
weight for that edge is 3.
Adjacency List Graph Representation
• A sparse graph is a graph where each vertex only has edges to a small portion of the other vertices in the Graph.
• An Adjacency List has an array that contains all the vertices in the graph, and each vertex has a Linked List with the edges
of respective vertices.

• In the adjacency list above, the vertices A to D are placed in an Array and each vertex in the array uses array index value.
• The Linked List contains the indexes to the adjacent vertices.
Contd….
• An Adjacency List can also represent a directed and weighted Graph.

• In the Adjacency List above, vertices are stored in an Array.


• Each vertex has a pointer to a Linked List with edges stored as i, w, where i is the index of the vertex the edge goes to
and w is the weight of that edge.
Graph Traversal
• Graph traversal algorithms are used to visit all the vertices and edges in a graph.
• The two most common traversal methods are Depth-First Search (DFS) and Breadth-First Search (BFS)
Depth First Search - DFS
• The DFS algorithm is a way to explore all the nodes (or vertices) in a graph or a tree.
• In the depth-first search algorithm, you start at a specific node and then go as far as possible along each branch before
going back (this is called backtracking).
• You keep doing this until you have visited all the nodes.

Fig. Maze Puzzle using DFS


DFS Algorithm Approaches
1. Recursive Approach
• The recursive approach uses function calls.
• The DFS algorithm calls itself for each unvisited neighbour.
• This method is like exploring a maze. You go down one path until you hit a dead end. Then, you backtrack
and try another path. The DFS algorithm keeps track of visited nodes to avoid loops.
• The recursive approach is simple but can use a lot of memory.
2. Iterative Approach
• The iterative approach uses a stack.
• The DFS algorithm pushes the starting node onto the stack.
• The DFS algorithm pops a node from the stack and visits it.
• The DFS algorithm pushes unvisited neighbours onto the stack. This process repeats until the stack is empty.
• The iterative approach is more memory-efficient than recursion. The DFS algorithm still explores all paths in
the graph.
DFS Iterative Algorithm DFS Recursive Algorithm

1. Push the starting node onto the stack. 1. Start at the initial node.
2. While the stack is not empty, pop a 2. Mark the current node as visited.
node from the stack. 3. For each unvisited neighbour, call the
3. If the node is unvisited, mark it as DFS function recursively.
visited. 4. Continue until all nodes connected to
4. Push all unvisited neighbours onto the starting node are visited.
the stack.
5. Repeat until the stack is empty.
DFS Recursive Approach
int adj[MAX][MAX]; // Adjacency matrix int main()
int visited[MAX]; // Visited array {
int n; // Number of vertices n = 5; // Example graph with 5 vertices

void DFS(int vertex) adj[0][1] = adj[1][0] = 1;


{ adj[0][2] = adj[2][0] = 1;
visited[vertex] = 1; adj[1][3] = adj[3][1] = 1;
printf("%d ", vertex); adj[1][4] = adj[4][1] = 1;
for (int i = 0; i < n; i++)
{ for (int i = 0; i < n; i++) {
if (adj[vertex][i] == 1 && !visited[i]) visited[i] = 0;
{ }
DFS(i);
} DFS(0); // Start DFS from vertex 0
} return 0;
} }
Iterative Approach
DFS(G,s)
for all v in V[G] do
visited[v] := false
end for

S := EmptyStack
visited[s] := true
Push(S,s)

while not Empty(S) do


u := Pop(S)
if there is at least one unvisited vertex in Adj[u] then
Pick w to be any unvisited vertex in Adj[u]
Push(S,u)
visited[w] := true
Push(S,w)
end if
end while
Properties
• Time Complexity
• The worst case occurs when the algorithm has to traverse through all the nodes in the graph.
• For directed graph as O( |E| + |V| ).
• For undirected graph as O( 2*|E| + |V| ).

• Space Complexity
• The space complexity of a depth-first search is O(V).
• Completeness
• This is a complete algorithm because if there exists a solution, it will be found regardless of the type of graph provided.
Applications

• Topological Sorting
• Finding Strongly Connected Components in a Graph
• Path Finding
• Detecting a graph's cycle
Breadth First Search - BFS
• BFS is a method for systematically visiting all nodes (vertices) in a graph or tree.
• It explores nodes level by level, starting from a given source node and moving outwards.
• BFS uses a queue (a FIFO - First-In, First-Out data structure) to keep track of the nodes to be explored.
• BFS is particularly useful for finding the shortest path in unweighted graphs (where all edges have the same
weight).
BFS Algorithm
1. Start: Begin at a designated starting node (or root node).
2. Enqueue: Add the starting node to the queue.
3. Iterate:
• Dequeue a node from the front of the queue.
• Mark the dequeued node as visited.
• Explore all unvisited neighbours of the dequeued node.
• Enqueue all unvisited neighbours into the queue.
4. Repeat: Continue steps 3 until the queue is empty.
BFS Implementation
int queue[MAX], front = -1, rear = -1; void BFS(int graph[MAX][MAX], int start, int int main()
n)
int visited[MAX] = {0}; {
{
int graph[MAX][MAX], n, start;
enqueue(start);
void enqueue(int v) printf("Enter the number of vertices: ");
visited[start] = 1;
{ scanf("%d", &n);
printf("BFS Traversal: ");
if (rear == MAX - 1) return; printf("Enter the adjacency matrix:\n");
while (front != -1)
if (front == -1) front = 0; for (int i = 0; i < n; i++)
{
queue[++rear] = v; for (int j = 0; j < n; j++)
int v = dequeue();
} scanf("%d", &graph[i][j]);
printf("%d ", v);
int dequeue()
for (int i = 0; i < n; i++)
{ printf("Enter the starting vertex: ");
{
if (front == -1) return -1; scanf("%d", &start);
if (graph[v][i] && !visited[i])
int v = queue[front++]; BFS(graph, start, n);
{
if (front > rear) front = rear = -1; return 0;
enqueue(i);
return v; }
visited[i] = 1;
}
} } } }
BFS Properties
• Shortest Path in Unweighted Graphs
• BFS guarantees finding the shortest path (in terms of number of edges) in an unweighted graph.
• Simple to Implement
• The algorithm is relatively straightforward to understand and implement.
• Systematic Exploration
• It explores the graph in a methodical way, ensuring all reachable nodes are visited.

• The time complexity of BFS is O(V + E).

• The space complexity of BFS is O(V).


Applications
• Pathfinding: Finding the shortest path in a graph or network.
• Web Crawling: Exploring websites in a breadth-first manner.
• Social Network Analysis: Analysing connections in social networks.
• Graph Traversal: Visiting all nodes in a graph or tree.
• Solving Puzzles: BFS can be used to find the shortest solution in puzzles like the Rubik's Cube or the shortest
path in a maze.
• Cycle Detection: BFS can be used to detect cycles in an undirected graph.
• Peer-to-Peer Networks: BFS is used to find all nodes within a certain number of hops in P2P networks.
Graph Edge Types
• While exploring a graph from a source node, edges can be of four types.
• Tree Edges
• Tree edges connect a parent to its child node. The terms parent and child come up in reference to the graph
exploration algorithm being used, i.e., when you use BFS or DFS to traverse a graph, a new child node you discover
by examining the neighbours of the parent node is connected via a tree edge.
• Only tree edges make up the BFS/DFS traversal. All other edges fall in the other three categories.
• Forward Edges
• An edge(x,y) where x appears before y and there is a path from x to y
• Back Edges
• An edge(x,y) where x appears after y and there is a path from y to x
• Cross Edges
• An edge(x,y) where no path from x to y or y to x.
Contd…
Detect Cycle in Undirected Graph - UG
• In an undirected graph, a cycle is a path that starts and ends at the same vertex,
traversing edges only once.
• Maintain a visited array to track visited nodes.
• During DFS/BFS, if you encounter an already visited node that is not the parent of the
current node, a cycle is detected.
• Graph: Nodes: {1, 2, 3, 4, 5}; Edges: {(1, 2), (2, 3), (3, 1), (2, 4), (4, 5)}
• Cycle: (1, 2, 3, 1) is a cycle.
• DFS/BFS Traversal: During traversal, you'll encounter node '3' as an adjacent node of '2',
and '3' is already visited, but not the parent of '2', indicating a cycle.
Detect Cycle in Directed Graph
• In a directed graph, a cycle is a path that starts and ends at the same vertex, following
the direction of the edges.
• Maintain a visited array and a recursion_stack array to track visited nodes and nodes
currently in the recursion stack.
• If you encounter a node that is already in the recursion_stack, a cycle is detected.
• Graph: Nodes: {1, 2, 3, 4}; Edges: {(1, 2), (2, 3), (3, 1), (2, 4)}.
• Cycle: (1, 2, 3, 1) is a cycle.
• DFS Traversal: During traversal, you'll encounter node '3' as an adjacent node of '2', and
'3' is already in the recursion_stack, indicating a cycle.
Cycle Detection using DFS for UG
void addEdge(int graph[n][n],int start,int end) int isCyclic(int graph[n][n], int vertices)
{ {
graph[start][end] = 1; int visited[n] = {0};
graph[end][start] = 1; // For undirected graph
} for (int i = 0; i < vertices; i++)
{
if (!visited[i])
int isCyclicDFS(int graph[n][n], int currentVertex, int parent, int visited[n]) {
{ if (isCyclicDFS(graph, i, -1, visited))
visited[currentVertex] = 1; return 1;
}
for (int i = 0; i < n; i++) { }
if (graph[currentVertex][i]) return 0;
{ }
if (!visited[i])
{ int main()
if (isCyclicDFS(graph, i, currentVertex, visited)) {
return 1; int vertices, edges;
}
else if (i != parent) { addEdge(graph, start, end);
return 1;
} if (isCyclic(graph, vertices))
} printf("The graph contains a cycle.\n");
} else
return 0; printf("The graph does not contain a cycle.\n");
}
return 0;
}
Topological Sort

• Topological sorting only exists in Directed Acyclic Graph (DAG).


• If the nodes of a graph are connected through directed edges and the graph does not
contain a cycle, it is called a directed acyclic graph(DAG).
• In topological sorting, node u will always appear before node v if there is a directed edge
from node u towards node v(u -> v).
• We will be solving it using the BFS/DFS traversal technique.
• Every DAG has one or more number of topological sorts.
• Topological sorting is widely used in scheduling applications, jobs, or tasks.
Topological Sort using BFS
void create_matrix()
{ int delete_queue() while(front <= rear)
int i,max_edges,start,dest; void insert_queue(int node) {
printf("\n Enter the number of vertices: "); int find_indegree(int node) del_node = delete_queue();
scanf("%d",&n); { topsort[j] = del_node;
int i,in_deg =0; j++;
for(i = 1; i <= max_edges; i++) { for(i = 1; i <= n; i++) for(node = 1; node <= n; node++)
printf("\n Enter edge %d (0 to quit):",i); { {
scanf("%d %d",&start,&dest); if( adj[i][node] == 1 ) if(adj[del_node][node] == 1 )
if((start == 0) && (dest == 0)) in_deg++; {
break; } adj[del_node][node]= 0;
if(start > n || dest > n|| start <= 0 || dest <= 0) return in_deg; indeg[node] = indeg[node] – 1;
{ } if(indeg[node]==0)
printf("\n Invalid edge"); void main() insert_queue(node);
i - -; { }
} int node,j = 0,del_node,I; }
else int topsort[10],indeg[10]; }
adj[start][dest] = 1; } } create_matrix(); printf("The topological sorting \n");
void display() printf("\n The adjacency matrix is:");
{ display(); for(node=0;i<j;node++)
int i,j; for(node = 1; node <= n; node++) printf("%d ",topsort[node]);
for(i=1;i<=n;i++) { }
{ indeg[node]=find_indegree(node);
for(j=1;j<=n;j++) if(indeg[node]==0)
printf("%d",adj[i][j]); insert_queue(node);
}} }
Topological Sort using BFS
Topological Sort using DFS
void AdjacencyMatrix(int a[][100], int n)
{ void topological_order(int n, int a[][100])
int i, j; {
for (i = 0; i < n; i++) { int i, u;
for (j = 0; j <= n; j++) { for (i = 0; i < n; i++) {
a[i][j] = 0; s[i] = 0;
} }
} j = 0;
} for (u = 0; u < n; u++) {
void addEdge(int a[][100], int start, int end) if (s[u] == 0) {
{ dfs(u, n, a);
a[start][end] = 1; }
a[end][start] = 1; }
} return;
void dfs(int start, int n, int a[][100]) }
{ void main()
int j; {
s[start] = 1; AdjacencyMatrix(a, n);
for (j = 0; j < n - 1; j++) { topological_order(n, a);
if (a[start][v] == 1 && s[j] == 0) {
dfs(j, n, a); for (i = n; i >= 1; i--) {
} printf("-->%d", top[i]);
} }
v += 1; return 0;
top[v] = u; }
}
Topological Sort using DFS
Shortest Path Algorithm
• Shortest path algorithms are broadly categorized into single-source and all-pairs algorithms.
• Single-source algorithms find the shortest paths from a single source node to all other nodes in a graph,
• while all-pairs algorithms find the shortest paths between every pair of nodes in the graph.
• Single-Source Algorithms:
1. Dijkstra's Algorithm:
• A greedy algorithm that finds the shortest paths from a single source node to all other nodes in a graph
with non-negative edge weights.
• It uses a priority queue to efficiently select the next node to explore.
2. Bellman-Ford Algorithm:
• A dynamic programming algorithm that can handle graphs with negative edge weights and detect
negative cycles.
• It works by repeatedly relaxing edges until no further changes occur.
Contd….

• All-Pairs Algorithms:
1. Floyd-Warshall Algorithm:
• A dynamic programming algorithm that finds the shortest paths between all pairs of nodes in a
graph.
• It can handle negative edge weights but not negative cycles.
2. Johnson's Algorithm:
• An algorithm that combines Dijkstra's algorithm with the Bellman-Ford algorithm to find
shortest paths between all pairs of nodes in a graph with potentially negative edge weights.
Contd…
• The shortest path from vertex D to vertex F in the Graph

1. D → E →C →F and weight 2+4+4 = 10


2. D → A → C → F and weight 4 + 3 + 4 =11
3. D → E → G → F and weight 2 + 5 + 5 =12
4. D → E → G → C → F and weight 2 + 5 + 5 + 4 =16
Dijkstra Algorithm
• Dijkstra’s algorithm, given by a Dutch scientist Edsger Dijkstra in 1959, is used to find the
shortest path tree.
• This algorithm is widely used in network routing protocols, most notably IS-IS and OSPF (Open
Shortest Path First).
• It is a well-known algorithm used to find the shortest path from a single source node to all other
nodes in a weighted graph with non-negative edge weights.
• Using adjacency matrix: O(V²)
• Using priority queue with adjacency list: O((V + E) log V)
Dijkstra Algorithm
• Key Features:
• Works on directed graphs.
• Handles only non-negative edge weights.
• Commonly used in network routing, GPS navigation, etc.
Limitation:
• Doesn’t work correctly if the graph contains negative weight edges.
Algorithm
int minDistance(int dist[], int visited[]) void dijkstra(int graph[V][V], int src)
{ {
int min = INT_MAX, min_index; int dist[V];
for (int v = 0; v < V; v++) int visited[V];
if (visited[v] == false && dist[v] <= min) for (int i = 0; i < V; i++)
{ dist[i] = INT_MAX;
min = dist[v]; visited[i] = 0;
min_index = v;
} dist[src] = 0;
return min_index; for (int count = 0; count < V - 1; count++)
} {
int u = minDistance(dist, visited);
void printSolution(int dist[]) visited[u] = 1;
{
printf("Vertex \t\t Distance from Source\n"); for (int v = 0; v < V; v++)
for (int i = 0; i < V; i++) if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v])
printf("%d \t\t %d\n", i, dist[i]); dist[v] = dist[u] + graph[u][v];
} }
printSolution(dist, V);
}
Example
Bellman Ford Algorithm

• The Bellman-Ford algorithm is best suited to find the shortest paths in a directed graph with
one or more negative edge weights from the source vertex to all other vertices.
• It works fine with negative edges as well as it is able to detect if the graph contains a
negative cycle.
• Relaxation means updating the shortest distance to a node if a shorter path is found through
another node.
• For an edge (u, v) with weight w:
• distance[v] > distance[u] + w), then update the distance[v] = distance[u] + w.

• In the bellman-ford algorithm, this process is repeated (V – 1) times for all the edges.
• This algorithm is only applicable for directed graphs.
Negative Weight Cycle

• Negative Cycle: A cycle is called a negative cycle if the sum of all its weights becomes negative.
• The following illustration is an example of a negative cycle:

• After V-1 iterations, it does one more iteration.


• If any edge can still be relaxed (i.e., shorter path found), negative weight cycle exists.
Bellman Ford Algorithm // Step 3: Check for negative-weight cycles
struct Edge for (int j = 0; j < edgeCount; j++)
{ {
int src, dest, weight; int u = edges[j].src;
}; int v1 = edges[j].dest;
void bellmanFord(struct Edge edges[], int v, int edgeCount, int w = edges[j].weight;
int s)
{
int dist[V]; if (dist[u] != INT_MAX && dist[u] + w < dist[v1])
for (int i = 0; i < v; i++) {
printf("Graph with negative weight cycle\n");
dist[i] = INT_MAX; return;
dist[s] = 0; }
}
// Step 2: Relax edges |V| - 1 times
// Print distances
for (int i = 1; i <= v - 1; i++) {
for (int j = 0; j < edgeCount; j++) { printf("Vertex\tDistance from Source\n");
int u = edges[j].src;
int v1 = edges[j].dest; for (int i = 0; i < vertices; i++)
int w = edges[j].weight; printf("%d\t%d\n", i, dist[i]);
}
if (dist[u] != INT_MAX && dist[u] + w < dist[v1])
dist[v1] = dist[u] + w; void main() {
} bellmanFord(edges, V, E, source);
} }
Example

Fig. Bellman Ford Example


Floyd Warshall Algorithm
• The Floyd-Warshall algorithm is a dynamic programming algorithm used to find the shortest
paths between all pairs of vertices in a weighted graph.
• Can handle negative edge weights, but no negative cycles.
• Time Complexity: O(V³), where V = number of vertices
• Use Cases:
• Network routing
• Map navigation
• Game development (AI pathfinding)
• Checking for negative weight cycles (diagonal elements < 0)
Steps for Algorithm

1. Create a distance matrix dist[][] where dist[i][j] is the weight of the edge from i to j.
2. Initialize:
dist[i][j] = 0 if i == j
dist[i][j] = weight if edge exists
dist[i][j] = ∞ if no edge

3. For each vertex k, update:


dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

4. Repeat for all combinations of i, j, and k.


Program for Floyd Warshall
void floydWarshall(int graph[V][V])
{ printf("Shortest distances between every pair of nodes:”);
int dist[V][V]; for (int i = 0; i < V; i++)
{
// Initialize distance matrix for (int j = 0; j < V; j++)
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) if (dist[i][j] == INF)
dist[i][j] = graph[i][j]; printf("%4s", "INF");
else
for (int k = 0; k < V; k++)
{ printf("%4d", dist[i][j]);
for (int i = 0; i < V; i++) }
{ printf("\n");
for (int j = 0; j < V; j++) }
{ }
if (dist[i][k] + dist[k][j] < dist[i][j]) int main()
dist[i][j] = dist[i][k] + dist[k][j]; {
} floydWarshall(graph);
}
} return 0;
}
Example
Contd…

You might also like