ALGO 1.0 Graph (Basics) (Slide 2)
ALGO 1.0 Graph (Basics) (Slide 2)
1
Graph
• Nonlinear data Structures.
• A graph G consists of two properties:
(a) A set V of elements called vertices or nodes.
(b) A set E of connectors called edges such that each edge e is identified as
e = (u,v) (unordered pair of vertices). Here is a edge between u and v and
they are said to be the adjacent nodes or neighbors .
Figure1: A graph G1
Definitions
• Isolated Node: A vertex u with no edges.
• Path: A path P of length n from a node u to node v is defined as a sequence n+1 nodes
such that P=(v0, v1, ….vn).
In graph G2
A B • Isolate Node: E
E • Path P from A to C : A -> B -> D -> C
• Length of the Path p : 3
C D
Figure2: Graph G2
3
Types of Graph
• Connected Graph: A graph is called connected if there is a simple path between any
two of its nodes.
Example:
A B
C D
C D • Edges: n(n-1)/2 = 6 4
• Tree Graph: A connected graph with no cycle. If a tree graph has m nodes, then there are
m-1 edges.
Example: A B
C D
• Unweighted Graph: A graph G is said to be un weighted if its edges are not assigned
any value.
A B
Example:
C D
• Weighted Graph: A labeled graph where each edge is assigned a numerical value w(e).
Example: 12
A B
5 2 7
C D
9
5
• Multigraph: A multigraph has the following properties:
A B
(a) Multiple Edges within the same nodes.
(b) Loops C D
Example: A B
C D
• Directed Graph: Each edge in graph has a direction such that e = (u,v), ie. e begins at u
and ends at v.
A B
Example:
C D
6
• Degree of a Node: No. of edges connected to a node.
(a) Indegree: No. of edges ending at a node.
(b) Outdegree: No. of edges beginning at a node.
Example:
B In graph G
A
Indeg(A)= 0 Outdeg(A)=2
Indeg(B)= 3 Outdeg(B)= 0
C D
Indeg(C)= 1 Outdeg(C)= 2
Note:
• A node u is called source if it has a positive outdegree and 0 indegree (A).
• A node u is called sink if it has a positive indegree and 0 outdegree (B).
• For a directed graph, a loop adds one to the indegree and one to the outdegree.
• For undirected graph, a loop adds two to the degree.
7
Representation of Graph
(1) Sequential Representation / Adjacency Matrix
aij = 1 if vi is adjacent to vj
0 otherwise
A B C D
Example: A B
A 0 1 1 0
B 0 0 0 0
C 0 1 0 1
C D D 0 1 0 0
8
Figure 4: A Directed Graph & Its Adjacency Matrix
Adjacency matrix representation
of a weighted graph
9
Linked Representation of a Graph
•Adjacency List:
An array of linked lists is used. Size of the array is equal to number of vertices. Let the
array be array[]. An entry array[i] represents the linked list of vertices adjacent to the ith
vertex. This representation can also be used to represent a weighted graph. The weights of
edges can be stored in nodes of linked lists. Following is adjacency list representation of
the above graph.
Example:
13