You are on page 1of 28

SE/SS * ZG 519

Data Structures and Algorithms Design


Graphs – Fundamentals
Revision-1.0

BITS Pilani Prof Vineet Garg


Work Integrated Learning Program Bangalore Professional Development Center
Session Outline

• Definition
• Fundamentals
• Abstract Data Type (ADT)
• Representation
• Operations

2
BITS Pilani, Pilani Campus
Definition
• A Graph is defined as a pair of two sets V and E.
V is a finite and non-empty set of vertices and E 1
is a set of pairs of vertices. E pairs are called
2 3
edges. V(G) and E(G) are called vertices and
edges of graph G respectively. Formally it is G1: An undirected graph
written as G = (V,E). V(G1) = {1, 2, 3}
E(G1) = { (1,2), (1,3), (2,3) }
• If there is no direction (no arrows) in the edges G1 = { V(G1), E(G1) }
of a graph, the graph is called Undirected
Graph, otherwise it is called Directed Graph (or
1
Digraph).
• In an undirected graph, if there is an edge from 2 3
vertex u to v, (u, v) or (v, u) represent the same
edge. So these duplicates edges are not written. G2: A directed graph
• In a directed graph, each edge is represented by V(G2) = {1, 2, 3}
<u, v>. Where u is the tail vertex and v is the E(G2) = { <1,2>, <1,3>, <3,2>, <2,1>,
head vertex. So, <u, v> and <v, u> represent <2,3>, <3,1>}
G2 = { V(G2), E(G2) }
different edges of a graph. 3
BITS Pilani, Pilani Campus
Complete Graph
A graph G(V,E) is said to be a Complete Graph, if there
exists an edge between every pair of vertices.

If there are n vertices in a complete graph, total edges:


– In undirected complete graph = n(n-1)/2
– In directed complete graph = n(n-1)
1
1
2 3
2 3
4
An Undirected Complete graph An Directed Complete graph
n=4 n=3
So, total count of edges = 4(4-1)/2 = 6 So, total count of edges = 3(3-1) = 6
4
BITS Pilani, Pilani Campus
Adjacency and Incidence

• In an undirected graph if (u, v) is an edge, the vertices u and v are


called adjacent and the edge (u, v) is incident on vertices u and v.

A Vertices A and B are adjacent and edge (A, B) is incident


on A and B.
B C Similarly, vertices A and C are adjacent and edge (A,C) is
incident on A and C.
No adjacency/incidence relationship between B and C.

• In a directed graph if <u, v> is a directed edge, then vertex u is adjacent to


v and v is adjacent from u. The edge <u, v> is incident to v and incident
from u.
A B C

Edges incident to vertex B are <A, B> and <C, B>.


Edge incident from vertex B is <B, A>.
In the edge <C, B>, vertex C is adjacent to vertex B and
vertex B is adjacent from vertex C.
5
BITS Pilani, Pilani Campus
Path

• A path from vertex u to vertex v in undirected graph G is a sequence


of vertices u, i1, i2, ……ik, v such that (u, i1), (i1, i2), ….(ik, v) are edges
in the graph G.
• If G is directed, then <u, i1>, <i1, i2>, ….<ik, v> are the edges in the
graph G for the path.
• The length of the path is count of edges on it.
1
1
2 3
2 3
One of the paths is 1, 2, 3. One of the paths is 1, 2, 3.
Edges on the path are (1,2) and (2, 3) The edges on the path are <1,2> and <2,3>
The path length = 2. The path length = 2.

6
BITS Pilani, Pilani Campus
Simple Path and Cycle

A simple path is a path in which all vertices except


possibly the first and last are distinct. If the first and the
last vertices are same (not distinct), the path is called
the cycle.

1 2 1, 2, 3, 4 is a simple path – all vertices are distinct.


1, 2, 3, 4, 1 is a simple path which is also a cycle.
(The first and the last vertices in a cycle will be the same)
4 3 1, 2, 3, 4, 1, 3 is not a simple path – vertices in the path are not distinct.

7
BITS Pilani, Pilani Campus
Connectivity
• A graph (directed or undirected) is said to be connected iff
there exists a path between every pair of vertices.
• If there exists at least one vertex that cannot be reached from
other vertices then such a graph is called disconnected graph.

1 2 1 1

3 4 2 3 2 3
5
4 5
No a connected graph. Connected Graph.
E.g. path from 3 to 1 does not exist. Paths exist between Undirected
E.g. path from 4 to 1 also does not exist. every pair of vertices. disconnected Graph

1 Directed disconnected graph, because


4 vertex 1 cannot be reached from vertex 4.
2 3
8
BITS Pilani, Pilani Campus
Degree
• The degree of a vertex is the count of edges incident on it.
• If the graph is directed, the in-degree of a vertex v is the count of edges for which
v is the head. The out-degree is the count of edges for which v is the tail.
• Degree = In-degree + Out-Degree.

A B C

In-degree of B = 2 1
Out-degree of B = 1
Degree of B = 3 2 3
In-degree of A = 1 Degree of each 1, 2 and 3 = 2
Out-degree of A = 1
Degree of A = 2

In-degree of C = 0
Out-degree of C = 1
Degree of C = 1 9
BITS Pilani, Pilani Campus
Subgraph

• A subgraph of G, is a graph H such that


V(H) is a subset of V(G), and
E(H) is a subset of E(G).
1

2 3
Given Graph G

1 1

2 2 3 2 3

Few subgraphs of G
10
BITS Pilani, Pilani Campus
Tree and Spanning Tree
• A connected graph that contains no cycle is tree. In other words - a graph is a tree
if and only if there is exactly one path between every pair of its vertices.
• A subgraph of G that contains all the vertices and is a tree is called Spanning Tree
of G.

1 1

2 3 2 3

1 1 4
4
2 3 2 3
1 1
4 4
2 3 2 3
A Tree of G
Given Graph G
4 4

Few Spanning Trees of G


11
BITS Pilani, Pilani Campus
Bipartite Graphs

For a graph G if the set of vertices can be partitioned into


two subsets A and B such that every edge in the graph G
has one vertex in A and another in B, the graph G is said to
be Bipartite Graph.
T1
Coaches C1 and C2 can coach more C1
than one teams out of T1 to T5. T2
All the edges have one vertex from
C2
coach set and another from team
set. T3

T4

T5
12
BITS Pilani, Pilani Campus
Weighted Graphs

• If the edges of a graph have weights assigned to them, they are


called weighted edges and such graphs are called Weighted Graphs.
• A weighted graph is also called a network.
• These weights may represent cost or distance or any other real
quantity in the real world applications.

1125 miles
25miles
New York Boston

935 miles 1050 miles


North Andover

Nashua Lowell
15 miles 36 miles
US Cities: Not to the scale

13
BITS Pilani, Pilani Campus
Graphs: Not Considered
Situations
• Self edges or loops.
• Multiple occurrences of the same edge.

1 1

2 3 2 3

Not a Graph. Vertices 1 and 3 have loops Not a Graph. Pair of vertices have multiple
occurrence of the same edge.

If they are present, algorithms should be modified appropriately.

14
BITS Pilani, Pilani Campus
Graph: ADT

AbstractDataType graph
{
objects
a set of vertices and a set of edges
operations
number vertices(); returns the count of vertices
number edges(); returns the count of vertices
boolean isEdge(i, j); returns TRUE if edge (i, j) exists,
else FALSE
number degree(i); returns the total degree of vertex i
eraseEdge(i, j); deleted the edge (i, j) from the graph
insertEdge(i, j); inserts an edge (i, j) in the graph
...... could be many more.
}

15
BITS Pilani, Pilani Campus
Representation
Array Based: Adjacency Matrix

For a graph G = (V, E) of n vertices where n > 1 the


Adjacency Matrix (A) of G is a two-dimensional n*n
array with the following properties:

Element A[i][j] = 1, iff there is an edge from i to j


0, otherwise

Note:
(1) For a directed graph, i is tail and j is head. So matrix cell A[i][j] = 1 if an edge
<i, j> exists in the graph.
(2) In an undirected graph if an edge (i, j) exits, then A[i][j]=1 and also A[j][j]=1.
16
BITS Pilani, Pilani Campus
Example
Adjacency Matrix: Undirected Graph

A B C D E
A B
A 0 1 1 0 1
C D B 1 0 0 1 0
E
C 1 0 0 0 1
D 0 1 0 0 1
Important Observations: E 1 0 1 1 0
(1) Matrix is symmetrical across the
diagonal. Notice A[i][j] = A[j][i]. Only
half of it can be saved to conserve the
space for a large graph. Why diagonal entries are 0?
(2) Diagonal entries are 0. Will that be the case
(3) Sum of the row is the degree for that always?
vertex. E.g.
Degree of A = 3
Degree of D = 2
Degree of E = 3
17
BITS Pilani, Pilani Campus
Example
Adjacency Matrix: Directed Graph

A B C D E
A B
A 0 1 1 0 0
C D B 0 0 0 1 0
E
C 0 0 0 0 0
D 0 0 0 0 1
Important Observations: E 1 0 1 0 0
(1) Matrix may or may not be symmetrical
across the diagonal.
(2) Diagonal entries are 0.
(3) Sum of the row is the out-degree for In which case the adjacency
that vertex. E.g. matrix of a directed graph
Out-degree of A = 2 will be symmetrical across
Out-degree of D = 1 the diagonal?
(4) Sum of the column is the in-degree for
that vertex. E.g.
In-degree of A = 1
In-degree of C = 2 18
BITS Pilani, Pilani Campus
Example
Adjacency Matrix: Weighted Graph (Network)

94 A B C D E
12 A B 16
23 A - 94 12 - -
C D B - - - 16 -
E
25 31 C - - - - -
D - - - - 31
E 23 - 25 - -

Element A[i][j] = Weight of <i, j>, iff <i, j> is a weighted edge in the graph
A very large number like infinity, otherwise

19
BITS Pilani, Pilani Campus
Representation
Linked List Based: Adjacency Lists

• The n rows of adjacency matrix are represented as n


chains.
• There is one chain for each vertex in the graph.
• The nodes in chain i represent the vertices that are
adjacent from vertex i.
• The vertex_id field of a chain node stores the index
of an adjacent vertex.
• Vertices in each chain are not required to be
ordered.

20
BITS Pilani, Pilani Campus
Example
Adjacency List: Undirected Graph

Important Observation:
A B The degree of any vertex is equal to
the count of nodes in its adjacency
C D list. E.g.:
E The Degree of A = 3
The Degree of C = 2
adjList

[A] B C E Null

[B] A D Null
[C] A E Null
[D] B E Null
[E] A C D Null

21
BITS Pilani, Pilani Campus
Example
Adjacency List: Directed Graph

Important Observation:
The out-degree of any vertex is
A B equal to the count of nodes in its
adjacency list. E.g.:
C D The Degree of A = 2
E The Degree of C = 0

adjList

[A] B C Null

[B] D Null
Is it possible to get the in-
[C] degree of any vertex in the
adjacency list representation?
[D] E Null If yes, how? If no, how to get?

[E] A C Null
22
BITS Pilani, Pilani Campus
Example
Adjacency List: Weighted Graph (Network)

94
12 A B 16 What is the major difference
23 between the adjacency list of
C D a weighted graph and an un-
E weighted graph?
25 31

adjList

[A] B 94 C 12 Null

[B] D 16 Null
[C]

[D] E 31 Null
[E] A 23 C 25 Null
23
BITS Pilani, Pilani Campus
Adjacency List
C/C++ Representation

• Each vertex node in the chain can be written as:


struct vertex
{
int vertex_id; // could be char or anything else also
long weight; // weight of an edge in the weighted graphs
struct vertex *link; // pointer to the next vertex
};
• The adjacency list can be written as:
struct vertex *adjList [MAX_VERTICES];
// adjList is an array of MAX_VERTICES elements, where each
// element is a pointer to a data of type struct vertex

24
BITS Pilani, Pilani Campus
Graph Operations
Breadth First Search (BFS) – Using a Queue.

• Visit origin vertex and put into a queue (FIFO).


• Repeatedly remove a vertex from the queue, visit its unvisited adjacent vertices,
put newly visited vertices into the queue and repeat the process.
• Origin vertex = 1, Queue = 1
• Remove 1 from the queue, visit its adjacent
unvisited vertices. Put them in the queue.
• Queue = 2, 4
2 • Remove 2 from the queue, visit its adjacent
3 unvisited vertices. Put them in the queue.
• Queue = 4, 3, 5, 6
1 • Remove 4 from the queue, visit its adjacent
unvisited vertices. Put them in the queue.
• Queue = 3, 5, 6
4
5
• Remove 3 from the queue – no unvisited
adjacent vertices.
• Queue = 5, 6
• Remove 5 from the queue – no unvisited
adjacent vertices.
6
• Queue = 6
• Remove 6 from the queue – no unvisited
adjacent vertices.
• Queue is empty. BFS Terminates.
BITS Pilani, Pilani Campus
Graph Operations
Depth First Search (DFS) – Using a Stack.

1. Let us say the DFS is to A

start from vertex = A. B C


2. It is pushed to the stack.
D E F G
3. If stack is not empty, pop
an element x. If x is not
H
visited already, mark it
D B
visited. If stack is empty,
G H E E E
the algorithm terminates. C F F F F F F
4. Push all the vertices (that A B B B B B B B B
are not visited) adjacent to
x in the stack.
Visited Nodes: A C G H D B E F
5. Repeat from point-3 above. 26
BITS Pilani, Pilani Campus
Exercise
1. Write a C/C++/Java program to store a user entered directed graph in adjacency matrix and perform
BFS and DFS on it. What is the time complexity of it?

2. What is the similarity between level order traversal of a tree and BFS of a graph?

3. Using stacks, write an algorithm to perform DFS of a graph.

4. You are designing a social networking website. To propose new friends to a subscriber X, what will
you prefer – DFS from X or BFS from X? Justify.

5. In the given graph, each vertex represents a work milestone. A milestone cannot be completed until
its prerequisite millstone(s) is(are) done, which is the tail vertex. Develop and algorithm which prints
the order of the milestones in order to complete the whole work. (Clue- refer topological sorting video)

27
BITS Pilani, Pilani Campus
Thank You

29
BITS Pilani, Pilani Campus

You might also like