Unit 9 graph

Dabbal Singh Mahara
Dabbal Singh MaharaLecturer Computer Science and Information Technology, Mid-West University, Nepal
Graph
1
By:
Dabal Singh Mahara
2017
Unit – 9 Graph
Contents Hours Marks
a) Introduction
b) Representation of Graph
• Array
• Linked list
c) Traversals
• Depth first Search
• Breadth first search
d) Minimum spanning tree
• Kruskal's algorithm
4 5
2
Introduction
• Graphs are a formalism for representing
relationships between objects.
– a graph G is represented as G = (V, E),
where,
• V is a set of vertices
• E is a set of edges
Balkhu
kalanki
Bafal
V = {Balkhu, Kalanki, Bafal}
E = {(Bafal, Kalanki),
(Balkhu, Kalanki),
(Kalanki, Balkhu)}
3
Graph
• A graph G = (V,E) is composed of:
V: set of vertices
E: set of edges connecting the vertices in V
• An edge e = (u,v) is a pair of vertices
• Example:
a b
c
d e
V= {a,b,c,d,e}
E= {(a,b),(a,c),(a,d),
(b,e),(c,d),(c,e),
(d,e)}
4
5
Graph ADT
Graph Terminology:
• Node
Each element of a graph is called node of a graph
• Edge
Line joining two nodes is called an edge.
It is denoted by e=[u,v] where u and v are adjacent vertices.
6
 Loop
An edge of the form (u, u) is said to be a loop. Here in figure [v2,v2]
 Multiedge
If x was y’s friend several times over, we can model this relationship
using multiedges. In figure e1 and e3.
Loop
e1
V1
V2e2V2
node
edge
e3
Adjacent and Incident
• If (v0, v1) is an edge in an undirected graph,
• v0 and v1 are adjacent
• The edge (v0, v1) is incident on vertices v0 and v1
• If <v0, v1> is an edge in a directed graph
• v0 is adjacent to v1, and v1 is adjacent from v0
• The edge <v0, v1> is incident on v0 and v1
7
• The degree of a vertex is the number of edges incident to that
vertex
• A node with degree 0 is known as isolated node.
• A node with degree 1 is known as pendant node.
• For directed graph,
• the in-degree of a vertex v is the number of edges
that have v as the head
• the out-degree of a vertex v is the number of edges
that have v as the tail
• if di is the degree of a vertex i in a graph G with n vertices and e
edges, the number of edges is
Degree of a Vertex
8
0
1 2
3 4 5 6
G1 G2
3
2
3 3
1 1 1 1
directed graph
in-degree
out-degree
0
1
2
G3
in:1, out: 1
in: 1, out: 2
in: 1, out: 0
0
1 2
3
33
3
Examples
9
10
Path
• Path: A sequence of
vertices v1,v2,. . .vk such
that consecutive vertices vi
and vi+1 are adjacent.
• Example: {1, 4, 3, 5, 2}
1
4 5
3
2
a b
c
d e
a b
c
d e
a b e d c b e d c
• Length of a path: Number of edges on the path
• simple path: The path with no repeated vertices
• cycle: simple path, except that the last vertex is the same as the
first vertex
a b
c
d e
b e c
11
• subgraph: subset of vertices and edges forming a graph
• connected component: maximal connected subgraph. E.g., the graph below has
3 connected components.
connected not connected
•connected graph: any two vertices are connected by some path
12
Types
• Graphs are generally classified as,
• Directed graph
• Undirected graph
13
Un Directed graph
• A graphs G is called directed graph if each edge has no
direction.
14
15
• Simple Graph
A graph in which there is no loop and no multiple edges between two nodes.
• Multigraph
The graph which has multiple edges between any two nodes but no loops is called
multigraph.
Types of Graph
Directed graph
• A graphs G is called directed graph if each edge has a
direction.
16
• Pseudograph
A graph which has loop is called pseudograph.
• Complete graph
A graph G is called complete, if every nodes are adjacent
with other node
• Weighted graph
If each edge of graph is assigned a number or value, then it
is weighted graph. The number is weight.
17
18
Why Use Graphs?
• Graphs serve as models of a wide range of objects:
– A roadmap
– A map of airline routes
– A layout of an adventure game world
– A schematic of the computers and connections that make up the Internet
– The links between pages on the Web
– The relationship between students and courses
– A diagram of the flow capacities in a communications or transportation network
19
Representations of Graphs
• To represent graphs, you need a convenient way to store the
vertices and the edges that connect them
• Two commonly used representations of graphs:
– The adjacency matrix
– The adjacency list
20
Adjacency Matrix
• If a graph has N vertices labeled 0, 1, . . . , N – 1:
– The adjacency matrix for the graph is a grid G with N rows and N columns
– Cell G[i][ j] = 1 if there’s an edge from vertex i to j
• Otherwise, there is no edge and that cell contains 0
• These are the simplest ways for representing graphs.
• Space requirement: O(n2)
• Adding and deleting edge: O(1)
• Testing an edge : O(1)
21
Adjacency Matrix (continued)
• If the graph is undirected, then four more cells are occupied by 1:
• If the vertices are labeled, then the labels can be stored in a
separate one-dimensional array
22
Adjacency List
• If a graph has N vertices labeled 0, 1, . . . , N – 1,
– The adjacency list for the graph is an array of N linked lists
– The ith linked list contains a node for vertex j if and only if there is an
edge from vertex i to vertex j
– It is suitable for sparse graphs i.e. graphs with the few edges
– Space required: O(V+E)
– Time for
• Testing edge to u O(dge(u))
• Finding adjacent vertices: O(deg(u))
• Insertion and deletion : O(deg(u))
23
Adjacency List (continued)
24
25
Exercise:
Construct Adjacency List and Adjacency Matrix
i. ii.
1
5 4
3
2
26
 One of the most fundamental graph problems is to traverse every edge and
vertex in a graph. Applications include:
 Printing out the contents of each edge and vertex.
 Counting the number of edges.
 Identifying connected components of a graph.
 Graph traversal algorithms visit the vertices of a graph, according to some
Strategy.
 Given G=(V,E) and vertex v, find all wV, such that w connects v
 Depth First Search (DFS): preorder traversal
 Breadth First Search (BFS): level order traversal
Graph Traversals
27
DFS
The basic idea is:
• Start from the given vertex and go as far as possible
i.e. search continues until the end of the path if not visited
already,
• Otherwise, backtrack and try another path.
• DFS uses stack to process the nodes.
Algorithm:
DFS(G,S)
{
T = { S };
Traverse(S);
}
Traverse(v)
{
for each w adjacent to v not yet in T
{
T = T U {w}; // add edge {v,w} in T
Traverse(w);
}
}
28
2
1
6
7
5
3
4
Example: DFS Tracing
Starting Vertex : 1
2
1
6
7
5
3
4
Visited Nodes: T = { }
2
1
6
7
5
3
4
T = { 1 }
T = { 1, 2 }
29
2
1
6
7
5
3
4
T = { 1, 2, 3 }
backtrack from 3
Visit next branch from 2
2
1
6
7
5
3
4
T = { 1, 2, 3, 4 }
2
1
6
7
5
3
4
T = { 1, 2, 3, 4, 7 }
30
T = { 1, 2, 3, 4, 7, 5 }
2
1
6
7
5
3
4
2
1
6
7
5
3
4
T = { 1, 2, 3, 4, 7, 5, 6 }
2
1
6
7
5
3
4
Final DFS tree.
31
Analysis:
• The complexity of the algorithm is greatly affected by
Traverse function we can write its running time in terms of
the relation,
T(n) = T(n-1) + O(n),
• At each recursive call a vertex is decreased and for each
vertex atmost n adjacent vertices can be there. So, O(n).
• Solving this we get, T(n) = O(n2). This is the case when
we use adjacency matrix.
• If adjacency list is used, T(n) = O(n + e), where e is
number of edges.
32
BFS
• This is one of the simplest methods of graph searching.
• Choose some vertex as a root or starting vertex.
• Add it to the queue. Mark it as visited and dequeue it from the queue.
• Add all the adjacent vertices of this node into queue.
• Remove one node from front and mark it as visited. Repeat this process until all the
nodes are visited.
BFS (G, S)
{
Initialize Queue, q = { }
mark S as visited;
enqueue(q, S);
while( q != Empty)
{
v = dequeue(q);
for each w adjacent to v
{
if w is not marked as visited
{
enqueue(q, w)
mark w as visited.
}
}
}
}
33
Analysis:
• This algorithms puts all the vertices in the queue and they
are accessed one by one.
• for each accessed vertex from the queue their adjacent
vertices are looked up for O(n) time (for worst case).
• Total time complexity , T(n) = O(n2) , in case of adjacency
matrix.
• T(n) = O(n +e), in case of adjacency list.
34
2
1
6
7
5
3
4
Example: BFS Algorithm Tracing
Solution:
2
1
6
7
5
3
4
 Starting vertex : 1
Visited: { 1 }
2
1
6
7
5
3
4
Visited: { 1,2, 3, 7, 5, 6 }
1
2 3 7 5 6Queue :
Queue :
35
2
1
6
7
5
3
4
 Dequeue front of queue. Add its all unvisited
adjacent nodes to the queue.
Queue 3 7 5 6 4
Visited : { 1, 2, 3, 7, 5, 6, 4 }
2
1
6
7
5
3
4
Queue
Visited : { 1, 2, 3, 7, 5, 6, 4 }
36
2
1
6
7
5
3
4
Final BFS Tree.
37
Spanning Tree
A spanning tree of a connected undirected graph G is a sub graph
T of without cycle G that connects all the vertices of G.
i.e. A spanning tree for a connected graph G is a tree containing
all the vertices of G
• A minimum spanning tree in a connected weighted graph is a
spanning tree that has the smallest possible sum of weights of its
edges.
• It represents the cheapest way of connecting all the nodes in G.
• It is not necessarily unique.
• Any time you want to visit all vertices in a graph at minimum cost
(e.g., wire routing on printed circuit boards, sewer pipe layout,
road planning…)
Minimum Spanning Trees
38
• Two algorithms that are used to construct the minimum
spanning tree from the given connected weighted graph of
given graph are:
 Kruskal's Algorithm
 Prim's Algorithm
MST Generating Algorithms
Kruskal's Algorithm
We have V as a set of n vertices and E as set of edges of graph G. The idea behind
this algorithm is:
• The nodes of the graph are considered as n distinct partial trees with one
node each.
• At each step of the algorithm, two partial trees are connected into single
partial tree by an edge of the graph.
• While connecting two nodes of partial trees, minimum weighted arc is
selected.
• After n-1 steps MST is obtained.
39
40
41
Algorithm:
Kruskal_MSt( G )
{
T = { V } // forest of n nodes
S = Set of edges sorted in non-decreasing order of weight
while( |T| < n-1 AND S != Empty)
{
select edge (u,v) from S in order
S = S – (u,v)
if (u,v) does not form cycle in T
T = T U {(u,v)}
}
}
Complexity Analysis
To form the forest of n trees takes O(n) time, the creation of S takes O(E.log E)
time and while loop executes O(n) time and the steps inside loop take almost
linear time.
So, total time – O(n) + O (E logE) +O(n log n)
42
2
1
6
7
5
3
4
18
7
10
15
8
9
11
13
7
Exercise: Trace Kruskals algorithm.
43
1 de 43

Recomendados

Unit ix graph por
Unit   ix    graph Unit   ix    graph
Unit ix graph Tribhuvan University
988 vistas42 diapositivas
Graph por
GraphGraph
GraphDr Sandeep Kumar Poonia
2.5K vistas78 diapositivas
Graph in Data Structure por
Graph in Data StructureGraph in Data Structure
Graph in Data StructureProf Ansari
678 vistas16 diapositivas
Graphs in Data Structure por
 Graphs in Data Structure Graphs in Data Structure
Graphs in Data Structurehafsa komal
2.2K vistas22 diapositivas
Graphss por
GraphssGraphss
Graphssfika sweety
4.1K vistas18 diapositivas
Data Structures - Lecture 10 [Graphs] por
Data Structures - Lecture 10 [Graphs]Data Structures - Lecture 10 [Graphs]
Data Structures - Lecture 10 [Graphs]Muhammad Hammad Waseem
6.4K vistas52 diapositivas

Más contenido relacionado

La actualidad más candente

Adjacency list por
Adjacency listAdjacency list
Adjacency listStefi Yu
4.5K vistas15 diapositivas
Graphs Algorithms por
Graphs AlgorithmsGraphs Algorithms
Graphs AlgorithmsKasun Ranga Wijeweera
1.1K vistas21 diapositivas
Problem Solving with Algorithms and Data Structure - Graphs por
Problem Solving with Algorithms and Data Structure - GraphsProblem Solving with Algorithms and Data Structure - Graphs
Problem Solving with Algorithms and Data Structure - GraphsYi-Lung Tsai
2.3K vistas68 diapositivas
Unit 2: All por
Unit 2: AllUnit 2: All
Unit 2: AllHector Zenil
1.1K vistas110 diapositivas
Graph representation por
Graph representationGraph representation
Graph representationTech_MX
37.2K vistas34 diapositivas
Graphs por
GraphsGraphs
GraphsSaurabh Mishra
1.5K vistas33 diapositivas

La actualidad más candente(20)

Adjacency list por Stefi Yu
Adjacency listAdjacency list
Adjacency list
Stefi Yu4.5K vistas
Problem Solving with Algorithms and Data Structure - Graphs por Yi-Lung Tsai
Problem Solving with Algorithms and Data Structure - GraphsProblem Solving with Algorithms and Data Structure - Graphs
Problem Solving with Algorithms and Data Structure - Graphs
Yi-Lung Tsai2.3K vistas
Graph representation por Tech_MX
Graph representationGraph representation
Graph representation
Tech_MX37.2K vistas
14 chapter9 graph_algorithmstopologicalsort_shortestpath por SSE_AndyLi
14 chapter9 graph_algorithmstopologicalsort_shortestpath14 chapter9 graph_algorithmstopologicalsort_shortestpath
14 chapter9 graph_algorithmstopologicalsort_shortestpath
SSE_AndyLi122 vistas
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring por Saurabh Kaushik
Graph Theory,Graph Terminologies,Planar Graph & Graph ColouringGraph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Saurabh Kaushik10.7K vistas
Data structure computer graphs por Kumar
Data structure computer graphsData structure computer graphs
Data structure computer graphs
Kumar 4.4K vistas
Attributed Graph Matching of Planar Graphs por Raül Arlàndez
Attributed Graph Matching of Planar GraphsAttributed Graph Matching of Planar Graphs
Attributed Graph Matching of Planar Graphs
Raül Arlàndez1.4K vistas
Graph terminologies & special type graphs por Nabeel Ahsen
Graph terminologies & special type graphsGraph terminologies & special type graphs
Graph terminologies & special type graphs
Nabeel Ahsen6.4K vistas
Graphs In Data Structure por Anuj Modi
Graphs In Data StructureGraphs In Data Structure
Graphs In Data Structure
Anuj Modi45.6K vistas

Similar a Unit 9 graph

Graph 1 por
Graph 1Graph 1
Graph 1International Islamic University
272 vistas90 diapositivas
LEC 12-DSALGO-GRAPHS(final12).pdf por
LEC 12-DSALGO-GRAPHS(final12).pdfLEC 12-DSALGO-GRAPHS(final12).pdf
LEC 12-DSALGO-GRAPHS(final12).pdfMuhammadUmerIhtisham
77 vistas73 diapositivas
10.graph por
10.graph10.graph
10.graphjashobhan pradhan
918 vistas30 diapositivas
Lecture 14 data structures and algorithms por
Lecture 14 data structures and algorithmsLecture 14 data structures and algorithms
Lecture 14 data structures and algorithmsAakash deep Singhal
1.8K vistas30 diapositivas
UNIT III.pptx por
UNIT III.pptxUNIT III.pptx
UNIT III.pptxSwarndeviKm
29 vistas74 diapositivas

Similar a Unit 9 graph(20)

141205 graphulo ingraphblas por graphulo
141205 graphulo ingraphblas141205 graphulo ingraphblas
141205 graphulo ingraphblas
graphulo665 vistas
141222 graphulo ingraphblas por MIT
141222 graphulo ingraphblas141222 graphulo ingraphblas
141222 graphulo ingraphblas
MIT601 vistas
358 33 powerpoint-slides_13-graphs_chapter-13 por sumitbardhan
358 33 powerpoint-slides_13-graphs_chapter-13358 33 powerpoint-slides_13-graphs_chapter-13
358 33 powerpoint-slides_13-graphs_chapter-13
sumitbardhan3.9K vistas
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma por PyData
Graph Analytics - From the Whiteboard to Your Toolbox - Sam LermaGraph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
Graph Analytics - From the Whiteboard to Your Toolbox - Sam Lerma
PyData862 vistas

Más de Dabbal Singh Mahara

Temporal databases por
Temporal databasesTemporal databases
Temporal databasesDabbal Singh Mahara
15.5K vistas29 diapositivas
Spatial databases por
Spatial databasesSpatial databases
Spatial databasesDabbal Singh Mahara
8.4K vistas57 diapositivas
Ordbms por
OrdbmsOrdbms
OrdbmsDabbal Singh Mahara
4.9K vistas39 diapositivas
Odbms concepts por
Odbms conceptsOdbms concepts
Odbms conceptsDabbal Singh Mahara
7.9K vistas52 diapositivas
Object database standards, languages and design por
Object database standards, languages and designObject database standards, languages and design
Object database standards, languages and designDabbal Singh Mahara
3.3K vistas61 diapositivas
Normalization por
NormalizationNormalization
NormalizationDabbal Singh Mahara
1.3K vistas67 diapositivas

Más de Dabbal Singh Mahara(20)

Object database standards, languages and design por Dabbal Singh Mahara
Object database standards, languages and designObject database standards, languages and design
Object database standards, languages and design
Dabbal Singh Mahara3.3K vistas

Último

Effect of deep chemical mixing columns on properties of surrounding soft clay... por
Effect of deep chemical mixing columns on properties of surrounding soft clay...Effect of deep chemical mixing columns on properties of surrounding soft clay...
Effect of deep chemical mixing columns on properties of surrounding soft clay...AltinKaradagli
6 vistas10 diapositivas
Literature review and Case study on Commercial Complex in Nepal, Durbar mall,... por
Literature review and Case study on Commercial Complex in Nepal, Durbar mall,...Literature review and Case study on Commercial Complex in Nepal, Durbar mall,...
Literature review and Case study on Commercial Complex in Nepal, Durbar mall,...AakashShakya12
72 vistas115 diapositivas
DevOps-ITverse-2023-IIT-DU.pptx por
DevOps-ITverse-2023-IIT-DU.pptxDevOps-ITverse-2023-IIT-DU.pptx
DevOps-ITverse-2023-IIT-DU.pptxAnowar Hossain
9 vistas45 diapositivas
fakenews_DBDA_Mar23.pptx por
fakenews_DBDA_Mar23.pptxfakenews_DBDA_Mar23.pptx
fakenews_DBDA_Mar23.pptxdeepmitra8
14 vistas34 diapositivas
Advances in micro milling: From tool fabrication to process outcomes por
Advances in micro milling: From tool fabrication to process outcomesAdvances in micro milling: From tool fabrication to process outcomes
Advances in micro milling: From tool fabrication to process outcomesShivendra Nandan
7 vistas18 diapositivas
MK__Cert.pdf por
MK__Cert.pdfMK__Cert.pdf
MK__Cert.pdfHassan Khan
10 vistas1 diapositiva

Último(20)

Effect of deep chemical mixing columns on properties of surrounding soft clay... por AltinKaradagli
Effect of deep chemical mixing columns on properties of surrounding soft clay...Effect of deep chemical mixing columns on properties of surrounding soft clay...
Effect of deep chemical mixing columns on properties of surrounding soft clay...
AltinKaradagli6 vistas
Literature review and Case study on Commercial Complex in Nepal, Durbar mall,... por AakashShakya12
Literature review and Case study on Commercial Complex in Nepal, Durbar mall,...Literature review and Case study on Commercial Complex in Nepal, Durbar mall,...
Literature review and Case study on Commercial Complex in Nepal, Durbar mall,...
AakashShakya1272 vistas
fakenews_DBDA_Mar23.pptx por deepmitra8
fakenews_DBDA_Mar23.pptxfakenews_DBDA_Mar23.pptx
fakenews_DBDA_Mar23.pptx
deepmitra814 vistas
Advances in micro milling: From tool fabrication to process outcomes por Shivendra Nandan
Advances in micro milling: From tool fabrication to process outcomesAdvances in micro milling: From tool fabrication to process outcomes
Advances in micro milling: From tool fabrication to process outcomes
Shivendra Nandan7 vistas
MSA Website Slideshow (16).pdf por msaucla
MSA Website Slideshow (16).pdfMSA Website Slideshow (16).pdf
MSA Website Slideshow (16).pdf
msaucla68 vistas
_MAKRIADI-FOTEINI_diploma thesis.pptx por fotinimakriadi
_MAKRIADI-FOTEINI_diploma thesis.pptx_MAKRIADI-FOTEINI_diploma thesis.pptx
_MAKRIADI-FOTEINI_diploma thesis.pptx
fotinimakriadi8 vistas
Update 42 models(Diode/General ) in SPICE PARK(DEC2023) por Tsuyoshi Horigome
Update 42 models(Diode/General ) in SPICE PARK(DEC2023)Update 42 models(Diode/General ) in SPICE PARK(DEC2023)
Update 42 models(Diode/General ) in SPICE PARK(DEC2023)
Tsuyoshi Horigome28 vistas
Instrumentation & Control Lab Manual.pdf por NTU Faisalabad
Instrumentation & Control Lab Manual.pdfInstrumentation & Control Lab Manual.pdf
Instrumentation & Control Lab Manual.pdf
NTU Faisalabad 5 vistas
zincalume water storage tank design.pdf por 3D LABS
zincalume water storage tank design.pdfzincalume water storage tank design.pdf
zincalume water storage tank design.pdf
3D LABS5 vistas
Machine Element II Course outline.pdf por odatadese1
Machine Element II Course outline.pdfMachine Element II Course outline.pdf
Machine Element II Course outline.pdf
odatadese19 vistas
SUMIT SQL PROJECT SUPERSTORE 1.pptx por Sumit Jadhav
SUMIT SQL PROJECT SUPERSTORE 1.pptxSUMIT SQL PROJECT SUPERSTORE 1.pptx
SUMIT SQL PROJECT SUPERSTORE 1.pptx
Sumit Jadhav 13 vistas
Introduction to CAD-CAM.pptx por suyogpatil49
Introduction to CAD-CAM.pptxIntroduction to CAD-CAM.pptx
Introduction to CAD-CAM.pptx
suyogpatil495 vistas
SPICE PARK DEC2023 (6,625 SPICE Models) por Tsuyoshi Horigome
SPICE PARK DEC2023 (6,625 SPICE Models) SPICE PARK DEC2023 (6,625 SPICE Models)
SPICE PARK DEC2023 (6,625 SPICE Models)
Tsuyoshi Horigome24 vistas
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx por lwang78
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx
2023Dec ASU Wang NETR Group Research Focus and Facility Overview.pptx
lwang7853 vistas

Unit 9 graph

  • 2. Unit – 9 Graph Contents Hours Marks a) Introduction b) Representation of Graph • Array • Linked list c) Traversals • Depth first Search • Breadth first search d) Minimum spanning tree • Kruskal's algorithm 4 5 2
  • 3. Introduction • Graphs are a formalism for representing relationships between objects. – a graph G is represented as G = (V, E), where, • V is a set of vertices • E is a set of edges Balkhu kalanki Bafal V = {Balkhu, Kalanki, Bafal} E = {(Bafal, Kalanki), (Balkhu, Kalanki), (Kalanki, Balkhu)} 3
  • 4. Graph • A graph G = (V,E) is composed of: V: set of vertices E: set of edges connecting the vertices in V • An edge e = (u,v) is a pair of vertices • Example: a b c d e V= {a,b,c,d,e} E= {(a,b),(a,c),(a,d), (b,e),(c,d),(c,e), (d,e)} 4
  • 6. Graph Terminology: • Node Each element of a graph is called node of a graph • Edge Line joining two nodes is called an edge. It is denoted by e=[u,v] where u and v are adjacent vertices. 6  Loop An edge of the form (u, u) is said to be a loop. Here in figure [v2,v2]  Multiedge If x was y’s friend several times over, we can model this relationship using multiedges. In figure e1 and e3. Loop e1 V1 V2e2V2 node edge e3
  • 7. Adjacent and Incident • If (v0, v1) is an edge in an undirected graph, • v0 and v1 are adjacent • The edge (v0, v1) is incident on vertices v0 and v1 • If <v0, v1> is an edge in a directed graph • v0 is adjacent to v1, and v1 is adjacent from v0 • The edge <v0, v1> is incident on v0 and v1 7
  • 8. • The degree of a vertex is the number of edges incident to that vertex • A node with degree 0 is known as isolated node. • A node with degree 1 is known as pendant node. • For directed graph, • the in-degree of a vertex v is the number of edges that have v as the head • the out-degree of a vertex v is the number of edges that have v as the tail • if di is the degree of a vertex i in a graph G with n vertices and e edges, the number of edges is Degree of a Vertex 8
  • 9. 0 1 2 3 4 5 6 G1 G2 3 2 3 3 1 1 1 1 directed graph in-degree out-degree 0 1 2 G3 in:1, out: 1 in: 1, out: 2 in: 1, out: 0 0 1 2 3 33 3 Examples 9
  • 10. 10 Path • Path: A sequence of vertices v1,v2,. . .vk such that consecutive vertices vi and vi+1 are adjacent. • Example: {1, 4, 3, 5, 2} 1 4 5 3 2 a b c d e a b c d e a b e d c b e d c • Length of a path: Number of edges on the path
  • 11. • simple path: The path with no repeated vertices • cycle: simple path, except that the last vertex is the same as the first vertex a b c d e b e c 11
  • 12. • subgraph: subset of vertices and edges forming a graph • connected component: maximal connected subgraph. E.g., the graph below has 3 connected components. connected not connected •connected graph: any two vertices are connected by some path 12
  • 13. Types • Graphs are generally classified as, • Directed graph • Undirected graph 13
  • 14. Un Directed graph • A graphs G is called directed graph if each edge has no direction. 14
  • 15. 15 • Simple Graph A graph in which there is no loop and no multiple edges between two nodes. • Multigraph The graph which has multiple edges between any two nodes but no loops is called multigraph. Types of Graph
  • 16. Directed graph • A graphs G is called directed graph if each edge has a direction. 16 • Pseudograph A graph which has loop is called pseudograph.
  • 17. • Complete graph A graph G is called complete, if every nodes are adjacent with other node • Weighted graph If each edge of graph is assigned a number or value, then it is weighted graph. The number is weight. 17
  • 18. 18 Why Use Graphs? • Graphs serve as models of a wide range of objects: – A roadmap – A map of airline routes – A layout of an adventure game world – A schematic of the computers and connections that make up the Internet – The links between pages on the Web – The relationship between students and courses – A diagram of the flow capacities in a communications or transportation network
  • 19. 19 Representations of Graphs • To represent graphs, you need a convenient way to store the vertices and the edges that connect them • Two commonly used representations of graphs: – The adjacency matrix – The adjacency list
  • 20. 20 Adjacency Matrix • If a graph has N vertices labeled 0, 1, . . . , N – 1: – The adjacency matrix for the graph is a grid G with N rows and N columns – Cell G[i][ j] = 1 if there’s an edge from vertex i to j • Otherwise, there is no edge and that cell contains 0 • These are the simplest ways for representing graphs. • Space requirement: O(n2) • Adding and deleting edge: O(1) • Testing an edge : O(1)
  • 21. 21 Adjacency Matrix (continued) • If the graph is undirected, then four more cells are occupied by 1: • If the vertices are labeled, then the labels can be stored in a separate one-dimensional array
  • 22. 22 Adjacency List • If a graph has N vertices labeled 0, 1, . . . , N – 1, – The adjacency list for the graph is an array of N linked lists – The ith linked list contains a node for vertex j if and only if there is an edge from vertex i to vertex j – It is suitable for sparse graphs i.e. graphs with the few edges – Space required: O(V+E) – Time for • Testing edge to u O(dge(u)) • Finding adjacent vertices: O(deg(u)) • Insertion and deletion : O(deg(u))
  • 24. 24
  • 25. 25 Exercise: Construct Adjacency List and Adjacency Matrix i. ii. 1 5 4 3 2
  • 26. 26  One of the most fundamental graph problems is to traverse every edge and vertex in a graph. Applications include:  Printing out the contents of each edge and vertex.  Counting the number of edges.  Identifying connected components of a graph.  Graph traversal algorithms visit the vertices of a graph, according to some Strategy.  Given G=(V,E) and vertex v, find all wV, such that w connects v  Depth First Search (DFS): preorder traversal  Breadth First Search (BFS): level order traversal Graph Traversals
  • 27. 27 DFS The basic idea is: • Start from the given vertex and go as far as possible i.e. search continues until the end of the path if not visited already, • Otherwise, backtrack and try another path. • DFS uses stack to process the nodes. Algorithm: DFS(G,S) { T = { S }; Traverse(S); } Traverse(v) { for each w adjacent to v not yet in T { T = T U {w}; // add edge {v,w} in T Traverse(w); } }
  • 28. 28 2 1 6 7 5 3 4 Example: DFS Tracing Starting Vertex : 1 2 1 6 7 5 3 4 Visited Nodes: T = { } 2 1 6 7 5 3 4 T = { 1 } T = { 1, 2 }
  • 29. 29 2 1 6 7 5 3 4 T = { 1, 2, 3 } backtrack from 3 Visit next branch from 2 2 1 6 7 5 3 4 T = { 1, 2, 3, 4 } 2 1 6 7 5 3 4 T = { 1, 2, 3, 4, 7 }
  • 30. 30 T = { 1, 2, 3, 4, 7, 5 } 2 1 6 7 5 3 4 2 1 6 7 5 3 4 T = { 1, 2, 3, 4, 7, 5, 6 } 2 1 6 7 5 3 4 Final DFS tree.
  • 31. 31 Analysis: • The complexity of the algorithm is greatly affected by Traverse function we can write its running time in terms of the relation, T(n) = T(n-1) + O(n), • At each recursive call a vertex is decreased and for each vertex atmost n adjacent vertices can be there. So, O(n). • Solving this we get, T(n) = O(n2). This is the case when we use adjacency matrix. • If adjacency list is used, T(n) = O(n + e), where e is number of edges.
  • 32. 32 BFS • This is one of the simplest methods of graph searching. • Choose some vertex as a root or starting vertex. • Add it to the queue. Mark it as visited and dequeue it from the queue. • Add all the adjacent vertices of this node into queue. • Remove one node from front and mark it as visited. Repeat this process until all the nodes are visited. BFS (G, S) { Initialize Queue, q = { } mark S as visited; enqueue(q, S); while( q != Empty) { v = dequeue(q); for each w adjacent to v { if w is not marked as visited { enqueue(q, w) mark w as visited. } } } }
  • 33. 33 Analysis: • This algorithms puts all the vertices in the queue and they are accessed one by one. • for each accessed vertex from the queue their adjacent vertices are looked up for O(n) time (for worst case). • Total time complexity , T(n) = O(n2) , in case of adjacency matrix. • T(n) = O(n +e), in case of adjacency list.
  • 34. 34 2 1 6 7 5 3 4 Example: BFS Algorithm Tracing Solution: 2 1 6 7 5 3 4  Starting vertex : 1 Visited: { 1 } 2 1 6 7 5 3 4 Visited: { 1,2, 3, 7, 5, 6 } 1 2 3 7 5 6Queue : Queue :
  • 35. 35 2 1 6 7 5 3 4  Dequeue front of queue. Add its all unvisited adjacent nodes to the queue. Queue 3 7 5 6 4 Visited : { 1, 2, 3, 7, 5, 6, 4 } 2 1 6 7 5 3 4 Queue Visited : { 1, 2, 3, 7, 5, 6, 4 }
  • 37. 37 Spanning Tree A spanning tree of a connected undirected graph G is a sub graph T of without cycle G that connects all the vertices of G. i.e. A spanning tree for a connected graph G is a tree containing all the vertices of G • A minimum spanning tree in a connected weighted graph is a spanning tree that has the smallest possible sum of weights of its edges. • It represents the cheapest way of connecting all the nodes in G. • It is not necessarily unique. • Any time you want to visit all vertices in a graph at minimum cost (e.g., wire routing on printed circuit boards, sewer pipe layout, road planning…) Minimum Spanning Trees
  • 38. 38 • Two algorithms that are used to construct the minimum spanning tree from the given connected weighted graph of given graph are:  Kruskal's Algorithm  Prim's Algorithm MST Generating Algorithms Kruskal's Algorithm We have V as a set of n vertices and E as set of edges of graph G. The idea behind this algorithm is: • The nodes of the graph are considered as n distinct partial trees with one node each. • At each step of the algorithm, two partial trees are connected into single partial tree by an edge of the graph. • While connecting two nodes of partial trees, minimum weighted arc is selected. • After n-1 steps MST is obtained.
  • 39. 39
  • 40. 40
  • 41. 41 Algorithm: Kruskal_MSt( G ) { T = { V } // forest of n nodes S = Set of edges sorted in non-decreasing order of weight while( |T| < n-1 AND S != Empty) { select edge (u,v) from S in order S = S – (u,v) if (u,v) does not form cycle in T T = T U {(u,v)} } } Complexity Analysis To form the forest of n trees takes O(n) time, the creation of S takes O(E.log E) time and while loop executes O(n) time and the steps inside loop take almost linear time. So, total time – O(n) + O (E logE) +O(n log n)
  • 43. 43