Unit III - Graphs
Unit III - Graphs
E-CSE
DEFINITION
A Graph G = (V,E) consists of a set of vertices(V) and set of edges (E). Each edge is a
pair (v,w), where v,w € V. Edges are sometimes referred to as arcs.
Example:
V = { V1,V2,V3,V4}
E = {E1, E2, E3, E4 }
REPRESENTATION OF GRAPHS
The two commonly used representations of Graphs are:
1. Adjacency Matrix
2. Adjacency List
1. Adjacency Matrix
Consider a graph C of n vertices and the matrix M. If there is an edge present between
vertices Vi and Vj, then M[i][j] = 1 else M[i][j] = 0. For an undirected graph, M[i][j] =
M[i][j = 1.
An Adjacency Matrix Representation for Undirected Graph
1. Adjacency List
The type in which a graph is created with the linked list is called adjacency list. So all the
advantages of linked list can be obtained in this type of graph. We need not have a prior
knowledge of maximum number of nodes.
The linked list representation of the head nodes and the adjacent nodes are given below.
Struct head
{
char data;
struct head *down;
struct head *next;
}
struct node
{
int ver;
struct node *link
}
TYPES OF GRAPHS
Graphs are classified into two types. They are:
i. Directed Graph.
ii. Undirected Graph.
i. Directed Graph: The directions are shown on the edges. Consider the graph given
below:
E1 V1
E2
V2 V3
E3 E4
V4
In the above graph, the edge E1 is in between the vertices V1 and V2. The Vertex V1 is
called the head and V2 is called the tail. It is also referred as digraph.
ii. Undirected Graph: In this type of graph, the edges are not directed.
Graph Terminologies:
Weighted Graph: A Graph is said to be weighted graph if every edge in the graph is
assigned a weight or value.
Unweighted Graph: A Graph is said to be unweighted graph if the edge in the graph is
not assigned a weight or value
Complete graph: If an undirected graph of n vertices consists of n(n-1)/2 number of
edges then it is called as complete graph.
The graph shown below is a complete graph.
Sub graph: A Sub graph G’ of graph G is a graph such that the set of vertices and
set of edges of G’ are proper subset of the set of edges of G.
A directed graph with this property is called as strongly connected. If a directed graph
is not strongly connected, but the underlying graph is connected, then the graph is said to
be weekly connected.
Length of a path: A path is a sequence of vertices w1, w2, w3, ..., wN, such that (wi, wi+1)
E for 1 < i < N. The length of a path is the number of edges on the path, which is N-1.
A simple path is one such that all vertices are distinct, except that the first and the last
could be the same.
Cycle: A cycle in a directed graph is a path of length at least 1 such that w1 = wN.
Indegree: The indegree of a vertex v is the number of edges entering into the vertex v.
Outdegree: The outdegree of a vertex v is the number of edges leaving the vertex v.
The indegree of a is 0.
The outdegree of a is 2.
Graph Traversal:
ALGORITHM
1. Create a graph.
2. Read the vertex from which you want to traverse the graph say V i.
3. Initialise the visited array to 1 at the index of V i
4. Insert the visited vertex Vi in the queue
5. Visit the vertex which is at the front of the queue. Delete it from the queue and place
its adjacent nodes in the queue.
In BFS the queue is maintained for storing the adjacent nodes and an array “visited” is
maintained for keeping the track of visited nodes. i.e. once a particular t is visited it
should not be revisited again.
Increment front, delete the node from Queue and print it.
ALGORITHM
Step 1: Choose any node in the graph. Designate it as the search node and mark it as
visited.
Step 2: Using the adjacency matrix of the graph, find a node adjacent to the search node
that has not been visited yet. Designate this as the new search node and mark it as visited.
Step 3: Repeat Step 2 using the new search node. If no node satisfying Step 2 can be
found, return to the previous search node and continue.
Step 4: When a return to the previous node in step 3 is impossible, the search from the
originally chosen search node is complete.
Step 5: If the graph still contains unvisited nodes, choose any node that has not been
visited and repeat Step 1 through Step 4.
Example:
In DFS the basic data structure for storing the adjacent vertices is stack.
Step 1: Start with vertex 1, print it so ‘1’ gets printed. Mark I as visited.
Void DFS(Vertex V)
{
visisted[V]=True;
for each W adjacent to V
if(!visisted[W])
DFS(W);
}
TOPOLOGICAL SORT
DEFINITION
A topological sort is an ordering of vertices in a directed acyclic graph, such that if there
is a path from vi to vj, then vj appears after vi in the ordering.
Topological ordering is not possible, if the graph has a cycle, since for two vertices v and
w in a cycle, v precedes w and w precedes v.
Step 1
Number of l’s present in each column of adjacency matrix represents the indegree of
corresponding vertex. In the given graph, indegree of a = 0, b=1, c=2 and d=2.
Step 2
Enqueue the vertex, whose indegree is ‘0’
Since vertex ‘a’ is 0, so place it on the queue.
Step 3
Dequeue the vertex ‘a’ from the queue and decrement the indegree’s of its adjacent
vertex’
Step 4
Dequeue the vertex ‘b’ from Q and decrement the indegree’s of its adjacent vertex.
Step 5
Dequeue the vertex c’ from Q and decrement the indegree’s of its adjacent vertex..
Step 6
Dequeue the vertex ‘d’.
The topological sort for the graph is the vertices which are dequeued is shown below.
The topological ordering is V1, V2, V5, V4, V3, V7, V6.
BICONNECTIVITY
EULER CIRCUITS
Definition:
An Eulerian path is a path in a graph which visits each edge exactly once. Similarly, an
Eulerian circuit is an Eulerian path which starts and ends on the same vertex. They were
first discussed by Leonhard Euler while solving the famous Seven Bridges of Königsberg
problem in 1736.
Given the graph on the right, is it possible to construct a path (or a cycle, i.e. a path
starting and ending on the same vertex) which visits each edge exactly once?
Graphs which allow the construction of so called Eulerian circuits are called Eulerian
graphs. Euler observed that a necessary condition for the existence of Eulerian circuits is
that all vertices in the graph have an even degree, and that for an Eulerian path either all,
or all but two (i.e., the two endpoint) vertices have an even degree.
Sometimes a graph that has an Eulerian path, but not an Eulerian circuit (in other words,
it is an open path, and does not start and end at the same vertex) is called semi-Eulerian.
Graph 1 Graph 2
Graph 3 Graph 4
Graph 5 Graph 6
What is the relationship between the nature of the vertices and the kind of path/circuit
that the graph contains?
There are mainly two algorithms exits to find Minimum spanning tree of any graph:
(i) Prims Algorithm
(ii) Kruskals Algorithm
Prim's algorithm
Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a
connected weighted undirected graph. This means it finds a subset of the edges that forms
a tree that includes every vertex, where the total weight of all the edges in the tree is
minimized.
The algorithm was developed in 1930 by Czech mathematician Vojtěch Jarník and later
independently by computer scientist Robert C. Prim in 1957 and rediscovered by Edsger
Dijkstra in 1959.
Therefore it is also sometimes called the DJP algorithm, the Jarník algorithm, or the
Prim–Jarník algorithm.
The only spanning tree of the empty graph (with an empty vertex set) is again the empty
graph. The following description assumes that this special case is handled separately.
The algorithm continuously increases the size of a tree, one edge at a time, starting with a
tree consisting of a single vertex, until it spans all vertices.
Input: A non-empty connected weighted graph with vertices V and edges E (the
weights can be negative).
Initialize: Vnew = {x}, where x is an arbitrary node (starting point) from V, Enew =
{}
Repeat until Vnew = V:
o Choose an edge (u, v) with minimal weight such that u is in Vnew and v is
not (if there are multiple edges with the same weight, any of them may be
picked)
o Add v to Vnew, and (u, v) to Enew
Output: Vnew and Enew describe a minimal spanning tree
EXAMPLE:
GRAPH Description
U Edge(u,v) V\U
{} {A,B,C,D,E,F,G}
(D,A) = 5 V
(D,B) = 9
{D} {A,B,C,E,F,G}
(D,E) = 15
(D,F) = 6
(D,B) = 9
(D,E) = 15
{A,D} {B,C,E,F,G}
(D,F) = 6 V
(A,B) = 7
(D,B) = 9
(D,E) = 15
{A,D,F} (A,B) = 7 V {B,C,E,G}
(F,E) = 8
(F,G) = 11
{A,B,D,F} (B,C) = 8 {C,E,G}
(B,E) = 7 V
(D,B) = 9 cycle
(D,E) = 15
(F,E) = 8
(F,G) = 11
(B,C) = 8
(D,B) = 9 cycle
(D,E) = 15 cycle
{A,B,D,E,F} (E,C) = 5 V {C,G}
(E,G) = 9
(F,E) = 8 cycle
(F,G) = 11
(B,C) = 8 cycle
(D,B) = 9 cycle
(D,E) = 15 cycle
{A,B,C,D,E,F} {G}
(E,G) = 9 V
(F,E) = 8 cycle
(F,G) = 11
(B,C) = 8 cycle
(D,B) = 9 cycle
{A,B,C,D,E,F,G} (D,E) = 15 cycle {}
(F,E) = 8 cycle
(F,G) = 11 cycle
Kruskal's algorithm
Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree
for a connected weighted graph. This means it finds a subset of the edges that forms a
tree that includes every vertex, where the total weight of all the edges in the tree is
minimized. If the graph is not connected, then it finds a minimum spanning forest (a
minimum spanning tree for each connected component). Kruskal's algorithm is an
example of a greedy algorithm.
Create a Spanning tree F (a set of vertices), where each vertex in the graph is a
separate tree.
Create a set S containing all the edges in the graph and sort them in ascending
order.
While S is nonempty and F is not yet spanning
Example:
Graph Description
In graph theory, the shortest path problem is the problem of finding a path between two
vertices (or nodes) in a graph such that the sum of the weights of its constituent edges is
minimized.
An example is finding the quickest way to get from one location to another on a road
map; in this case, the vertices represent locations and the edges represent segments of
road and are weighted by the time needed to travel that segment.
There are several variations according to whether the given graph is undirected, directed,
or mixed. For undirected graphs, the shortest path problem can be formally defined as
follows. Given a weighted graph (that is, a set V of vertices, a set E of edges, and a real-
valued weight function f : E → R), and elements v and v' of V, find a path P from v to a v'
of V so that
The problem is also sometimes called the single-pair shortest path problem, to
distinguish it from the following variations:
Dijkstra's algorithm
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956
and published in 1959, is a graph search algorithm that solves the single-source shortest
path problem for a graph with nonnegative edge path costs, producing a shortest path
tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.
For a given source vertex (node) in the graph, the algorithm finds the path with lowest
cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used
for finding costs of shortest paths from a single vertex to a single destination vertex by
stopping the algorithm once the shortest path to the destination vertex has been
determined.
For example, if the vertices of the graph represent cities and edge path costs represent
driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm
can be used to find the shortest route between one city and all other cities. As a result, the
shortest path first is widely used in network routing protocols, most notably IS-IS and
OSPF (Open Shortest Path First).
Dijkstra's original algorithm does not use a min-priority queue and runs in O(|V|2). The
idea of this algorithm is also given in (Leyzorek et al. 1957). The common
implementation based on a min-priority queue implemented by a Fibonacci heap and
running in O(|E| + |V| log |V|) is due to (Fredman & Tarjan 1984). This is asymptotically
the fastest known single-source shortest-path algorithm for arbitrary directed graphs with
unbounded nonnegative weights. (For an overview of earlier shortest path algorithms and
later improvements and adaptations, see: Single-source shortest-paths algorithms for
directed graphs with nonnegative weights.)
Algorithm
Let the node at which we are starting be called the initial node. Let the distance of node
Y be the distance from the initial node to Y. Dijkstra's algorithm will assign some initial
distance values and will try to improve them step by step.
1. Assign to every node a tentative distance value: set it to zero for our initial node
and to infinity for all other nodes.
2. Mark all nodes except the initial node as unvisited. Set the initial node as current.
Create a set of the unvisited nodes called the unvisited set consisting of all the
nodes except the initial node.
3. For the current node, consider all of its unvisited neighbors and calculate their
tentative distances. For example, if the current node A is marked with a distance
of 6, and the edge connecting it with a neighbor B has length 2, then the distance
to B (through A) will be 6+2=8. If this distance is less than the previously
recorded distance, then overwrite that distance. Even though a neighbor has been
examined, it is not marked as visited at this time, and it remains in the unvisited
set.
4. When we are done considering all of the neighbors of the current node, mark the
current node as visited and remove it from the unvisited set. A visited node will
never be checked again; its distance recorded now is final and minimal.
5. The next current node will be the node marked with the lowest (tentative)
distance in the unvisited set.
6. If the unvisited set is empty, then stop. The algorithm has finished. Otherwise, set
the unvisited node marked with the smallest tentative distance as the next "current
node" and go back to step 3.
In a given graph, and starting node, Dijkstra's Algorithm discovers the shortest
path from the starting node to all other nodes.
Figure 1 displays the graph: nodes are black circles labelled a-f, a path is a black line
connecting two nodes, each path has an associated length beside it (the numbers). The
lengths are not to scale.
Node 'a' is our starting node, we want to find the shortest path to all other nodes in the
graph. To do this, we generate a table. This table has the distance to all the nodes in the
graph, from the perspective of the starting node 'a'.
As can be seen from Table 1, the initial entries for the distances are all set to infinity (or
some notional maximum value). This ensures that any path found will be shorter than the
initial value stored in the table.
The node 'a' is the starting node, as such we examine all the possible paths away from this
node first. The options are as follows:
These values are used to update the graph table, Table 1, which becomes:
These values are then compared to the values stored in the Table 3. It can be seen that
both of these values are less than the current values stored in the table, as such table 3
becomes:
This step has illustrated one of the advantages of dijkstra's algorithm: the route to node 'b'
is not the most direct route, but it is the shortest route; Dijkstra's Algorithm can find the
shortest route, even when that route is
not the most direct route.
IMPORTANT:
As these value are being updated, the route that accompanies these distances also needs
to be stored.
Once again, the table of paths is consulted, and the shortest path to a node that has not
been visited is found. This node becomes the next current node. In this case, that is node
'd'.
f 14
The table of all paths is updated to reflect that, and the node 'd' is marked as visited, this
locks in the shortest path to node 'd' also:
It can be seen from table 8 above, that the next nearest node to node 'a' is node 'b'. All
paths from node 'b' are examined next. In this instance, we have a path to a node that is
marked as visited: node 'c', we already know that the path to node 'c' is as short as it can
get (the node being marked as visited is
the marker for this).
Applications of Graph:
Graphs and Graph theory find various application in many real life applications. Some of
them are listed below:
1. The link structure of a website could be represented by a directed graph: the vertices
are the web pages available at the website and a directed edge from page A to page B
exists if and only if A contains a link to B.
2. A graph structure can be extended by assigning a weight to each edge of the graph.
Graphs with weights, or weighted graphs, are used to represent structures in which pair
wise connections have some numerical values. For example if a graph represents a road
network, the weights could represent the length of each road. A digraph with weighted
edges in the context of graph theory is called a network.
3. Networks have many uses in the practical side of graph theory, network analysis (for
example, to model and analyze traffic networks). Within network analysis, the definition
of the term "network" varies, and may often refer to a simple graph.
Many applications of graph theory exist in the form of network analysis. These split
broadly into three categories.
ii. Secondly, analysis to find a measurable quantity within the network, for example, for a
transportation network, the level of vehicular flow within any portion of it.