Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf

Graph (I)
Bruce Nan
Email: xiaomingnan@gmail.com
Seven Bridges of Königsberg
 The Seven Bridges of Königsberg is a notable historical
problem in mathematics. The problem was to find a walk
through the city that would cross each bridge once and only
once. The islands could not be reached by any route other
than the bridges, and every bridge must have been crossed
completely every time.
Euler’s Analysis
 During any walk in the graph, the
number of times one enters a non-
terminal vertex equals the number of
times one leaves it.
 If every bridge is traversed exactly
once it follows that for each land mass
(except possibly for the ones chosen
for the start and finish), the number of
bridges touching that land mass is
even.
 However, all the four land masses in
the original problem are touched by an
odd number of bridges (one is touched
by 5 bridges and the other three by 3).
Since at most two land masses can
serve as the endpoints of a putative
walk, the existence of a walk traversing
each bridge once leads to a
contradiction.
C
A
D
B
Eulerian path
 In graph theory, an Eulerian trail is a trail in
a graph which visits every edge exactly once.
Similarly, an Eulerian circuit or Eulerian
cycle is a Eulerian trail which starts and ends
on the same vertex.
What is a 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. Edges are
sometimes referred to as arcs.
 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)}
Applications
 electronic circuits
 networks (roads, flights, communications)
CS16
LAX
JFK
LAX
DFW
STL
HNL
FTL
Directed Vs. Undirected Graph
 An undirected graph is one in which the pair
of vertices in a edge is unordered, (v0, v1) =
(v1,v0)
 A directed graph is one in which each edge is
a directed pair of vertices, <v0, v1> != <v1,v0>
Terminology: Adjacent
 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
Degree of a Vertex
 The degree of a vertex is the number of edges
incident to that vertex
 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
e di
n
=
−
∑
( ) /
0
1
2
Why? Since adjacent vertices each
count the adjoining edge, it will be
counted twice
Examples 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
3
3
3
Path
 path: sequence of
vertices v1,v2,. . .vk such
that consecutive vertices
vi and vi+1 are adjacent.
The length of such a path
is the number of edges
on the path, which is
equal to k-1. We allow a
path from a vertex to
itself; if this path contains
no edges, then the path
lenght is 0.
3
3 3
3
2
a b
c
d e
a b
c
d e
a b e d c b e d c
 simple path: 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
a c d a
a b
c
d e
More Terminology
 An undirected graph is connected if there is a
path from every vertex to every other vertex.
 A directed graph with this property is called
strongly connected.
More Terminology
 subgraph: subset of vertices and edges forming
a graph
 connected component: maximal connected
subgraph. E.g., the graph below has 3
connected components.
Examples
0 0
1 2 3
1 2 0
1 2
3
(i) (ii) (iii) (iv)
(a) Some of the subgraph of G1
0 0
1
0
1
2
0
1
2
(i) (ii) (iii) (iv)
(b) Some of the subgraph of G3
0
1 2
3
G1
0
1
2
G3
Tree and Forests
 tree - connected graph without cycles
 forest - collection of trees
tree
forest
tree
tree
tree
Examples
V1 V2
V3
V4 V5
Tree
V1 V2
V3
V4 V5
V1 V2
V3
V4 V5
V6
V7
Forest
V1 V2 V3
V4 V5
V6
V7
Connectivity
 Let n = #vertices, and m = #edges
 A complete graph: one in which all pairs of vertices are
adjacent
 How many total edges in a complete graph?
 Each of the n vertices is incident to n-1 edges,
however, we would have counted each edge twice!
Therefore, intuitively, m = n(n -1)/2.
 Therefore, if a graph is not complete, m < n(n -1)/2
n = 5
m = (5 ∗ 4)/2 = 10
More Connectivity
n = #vertices
m = #edges
 For a tree m = n - 1
n = 5
m = 4
If m < n - 1, G
is not connected
n = 5
m = 3
How to store a Graph?
 Adjacent Matrix
 Adjacent Lists
Adjacent Matrix
 Let G=(V,E) be a graph with n vertices.
 The adjacency matrix of G is a two-dimensional
n by n array, say adj_mat
 If the edge (vi, vj) is in E(G), adj_mat[i][j]=1
 If there is no such edge in E(G), adj_mat[i][j]=0
 The adjacency matrix for an undirected graph is
symmetric; the adjacency matrix for a digraph
need not be symmetric
Examples for Adjacency Matrix
0
1
1
1
1
0
1
1
1
1
0
1
1
1
1
0












0
1
0
1
0
0
0
1
0










0
1
1
0
0
0
0
0
1
0
0
1
0
0
0
0
1
0
0
1
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
1
0
1
0
0
0
0
0
0
1
0
1
0
0
0
0
0
0
1
0


























G1
G2
G4
0
1 2
3
0
1
2
1
0
2
3
4
5
6
7
symmetric
More Adjacent Matrix
 How to get the degree of vertex i?
V1
V3
V4
V2
V1 V2 V3 V4
vertex=
0 1 0 1
1 0 1 1
0 1 0 0
1 1 0 0
arc=
V1 V2 V3 V4
V1
V2
V3
V4
The number of non-zero data in ith row
More Adjacent Matrix
How to ensure if there is edge on vi and vj?
V1
V3
V4
V2
V1 V2 V3 V4
vertex=
0 1 0 1
1 0 1 1
0 1 0 0
1 1 0 0
arc=
V1 V2 V3 V4
V1
V2
V3
V4
Test whether arc[i][j] is 1
More Adjacent Matrix
V1
V3
V4
V2
V1 V2 V3 V4
vertex=
0 1 0 1
1 0 1 1
0 1 0 0
1 1 0 0
arc=
V1 V2 V3 V4
V1
V2
V3
V4
How to find all adjacent vertices of vi?
Traverse all ith row elements, if arc[i][j] is 1, vj is
the adjacent vetex of vi
Digraph Adjacent Matrix
V1 V2
V3 V4
V1 V2 V3 V4
vertex=
0 1 1 0
0 0 0 0
0 0 0 1
1 0 0 0
arc=
V1 V2 V3 V4
V1
V2
V3
V4
How to find the out degree of vi?
sum all elements on ith row
Digraph Adjacent Matrix
How to find the in degree of vi?
sum all elements on ith column
V1 V2
V3 V4
V1 V2 V3 V4
vertex=
0 1 1 0
0 0 0 0
0 0 0 1
1 0 0 0
arc=
V1 V2 V3 V4
V1
V2
V3
V4
More Adjacent Matrix
 From the adjacency matrix, to determine the
connection of vertices is easy
 The degree of a vertex is
 For a digraph (= directed graph), the row sum is the
out_degree, while the column sum is the in_degree
ind vi A j i
j
n
( ) [ , ]
=
=
−
∑
0
1
adj mat i j
j
n
_ [ ][ ]
=
−
∑
0
1
outd vi A i j
j
n
( ) [ , ]
=
=
−
∑
0
1
Create Adjacent Matrix
buildGraph(int a[ ], int n, int e)
{
vertexNum=n; arcNum=e;
for (i=0; i<vertexNum; i++)
vertex[i]=a[i];
for (i=0; i<vertexNum; i++) //initialization
for (j=0; j<vertexNum; j++)
arc[i][j]=0;
for (k=0; k<arcNum; k++) //get each edge
{
cin>>i>>j; //the vertices of the edge
arc[i][j]=1; arc[j][i]=1; //adjacency
}
}
Practice Time
 Implement following functions
 Given a graph, create the adjacent matrix
 Insert edges between u and v
 Delete edge between u and v
 Output the degree of u
 Output all the adjacent vertices of u
Adjacency Lists
 The space complexity of Adjacent Matrix?
 Idea for Adjacency List:
 For each vertex vi, using a list to store all adjacent
vertices with vi, which is referred as vi’s edge list
 Implementation
 Vector array
0
1
2
3
0
1
2
0
1
2
3
4
5
6
7
1 2 3
0 2 3
0 1 3
0 1 2
G1
1
0 2
G3
1 2
0 3
0 3
1 2
5
4 6
5 7
6
G4
0
1 2
3
0
1
2
1
0
2
3
4
5
6
7
An undirected graph with n vertices and e edges ==> n head nodes and 2e list node
More Adjacency List
degree of a vertex in an undirected graph
–# of nodes in adjacency list
# of edges in a graph
–determined in O(n+e)
out-degree of a vertex in a directed graph
–# of nodes in its adjacency list
in-degree of a vertex in a directed graph
–traverse the whole data structure
Graph Traversal
 Problem: Search for a certain node or
traverse all nodes in the graph
 Depth First Search
 Once a possible path is found, continue the
search until the end of the path
 Breadth First Search
 Start several paths at a time, and advance in each
one step at a time
 Topological Sorting
Graph Traversal
 Both graph traversal procedures share one fundamental
idea, namely, that it is necessary to mark the vertices we
have seen before so we don’t try to explore them again.
Otherwise we get trapped in a maze and can’t find our
way out.
 BFS and DFS differ only in the order in which they
explore vertices.
Breadth-First Search (BFS)
 A Breadth-First Search (BFS) traverses a connected component
of a graph, and in doing so defines a spanning tree with several
useful properties.
 The starting vertex s has level 0, and, as in DFS, defines that
point as an “anchor.”
 In the first round, the string is unrolled the length of one edge,
and all of the edges that are only one edge away from the anchor
are visited.
 These edges are placed into level 1
 In the second round, all the new edges that can be reached by
unrolling the string 2 edges are visited and placed in level 2.
 This continues until every vertex has been assigned a level.
 The label of any vertex v corresponds to the length of the
shortest path from s to v.
BFS - A Graphical Representation
M N O P
I J K L
E F G H
A B C D
0
M N O P
I J K L
E F G H
A B C D
0 1
M N O P
I J K L
E F G H
A B C D
0 1 2 3
M N O P
I J K L
E F G H
A C D
B
0 1 2
V1
V3
V2
V4 V5 V6 V7
V8
Result: V1
V1
V1
V3
V2
V4 V5 V6 V7
V8
V1
V2
V2 V3
V3
Result:
V1
V3
V2
V4 V5 V6 V7
V8
V1 V2 V3
V3
V4
V4
V5
V5
Result:
V1
V3
V2
V4 V5 V6 V7
V8
V1 V2 V3 V4
V4
V5
V5
V6
V6
V7
V7
Result:
V1
V3
V2
V4 V5 V6 V7
V8
V1 V2 V3 V4 V5
V5
V6
V6
V7
V7 V8
V8
Result:
Code – BFS Using Adjacent Matrix
template <class T>
void MGraph::BFSTraverse(int v)
{
front=rear=-1; //Assuming no overflow
cout<<vertex[v]; visited[v]=1; Q[++rear]=v;
while (front!=rear)
{
v=Q[++front];
for (j=0; j<vertexNum; j++)
if (arc[v][j]==1 && visited[j]==0 ) {
cout<<vertex[j]; visited[j]=1; Q[++rear]=j;
}
}
}
Code – BFS Using Adjacent List
template <class T>
void ALGraph::BFSTraverse(int v)
{
front=rear=-1;
cout<<adjlist[v].vertex; visited[v]=1; Q[++rear]=v;
while (front!=rear)
{
v=Q[++front]; p=adjlist[v].firstedge;
while (p!=NULL)
{
j= p->adjvex;
if (visited[j]==0) {
cout<<adjlist[j].vertex; visited[j]=1; Q[++rear]=j;
}
p=p->next;
}
}
}
BFS Usage
 Finding a path
In a maze, how to find a path from the start to the
end using least steps?
 Exploiting traversal
1 de 45

Recomendados

Graphs in data structures por
Graphs in data structuresGraphs in data structures
Graphs in data structuresSavit Chandra
1K vistas32 diapositivas
Graphs por
GraphsGraphs
Graphsamudha arul
175 vistas45 diapositivas
Lecture 5b graphs and hashing por
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashingVictor Palmar
1.2K vistas56 diapositivas
Graph por
GraphGraph
GraphMudassar Mushtaq
413 vistas52 diapositivas
Unit 2: All por
Unit 2: AllUnit 2: All
Unit 2: AllHector Zenil
1.1K vistas110 diapositivas
Graph in Data Structure por
Graph in Data StructureGraph in Data Structure
Graph in Data StructureProf Ansari
678 vistas16 diapositivas

Más contenido relacionado

Similar a Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf

Graph in data structure por
Graph in data structureGraph in data structure
Graph in data structurePooja Bhojwani
198 vistas28 diapositivas
Graphs por
GraphsGraphs
GraphsSpeaking Technology
2K vistas20 diapositivas
Graph ASS DBATU.pptx por
Graph ASS DBATU.pptxGraph ASS DBATU.pptx
Graph ASS DBATU.pptxARVIND SARDAR
4 vistas151 diapositivas
Elements of Graph Theory for IS.pptx por
Elements of Graph Theory for IS.pptxElements of Graph Theory for IS.pptx
Elements of Graph Theory for IS.pptxmiki304759
54 vistas48 diapositivas
Graphs por
GraphsGraphs
GraphsKomalPaliwal3
66 vistas44 diapositivas
Ass. (3)graph d.m por
Ass. (3)graph d.mAss. (3)graph d.m
Ass. (3)graph d.mSyed Umair
566 vistas9 diapositivas

Similar a Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf(20)

Elements of Graph Theory for IS.pptx por miki304759
Elements of Graph Theory for IS.pptxElements of Graph Theory for IS.pptx
Elements of Graph Theory for IS.pptx
miki30475954 vistas
Ass. (3)graph d.m por Syed Umair
Ass. (3)graph d.mAss. (3)graph d.m
Ass. (3)graph d.m
Syed Umair566 vistas
Graphs In Data Structure por Anuj Modi
Graphs In Data StructureGraphs In Data Structure
Graphs In Data Structure
Anuj Modi1.1K vistas
Graphs In Data Structure por Anuj Modi
Graphs In Data StructureGraphs In Data Structure
Graphs In Data Structure
Anuj Modi45.6K vistas
Lecture 1--Graph Algorithms -- Basics.pptx por ChandanGiri21
Lecture 1--Graph Algorithms -- Basics.pptxLecture 1--Graph Algorithms -- Basics.pptx
Lecture 1--Graph Algorithms -- Basics.pptx
ChandanGiri2136 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
Graph theory concepts complex networks presents-rouhollah nabati por nabati
Graph theory concepts   complex networks presents-rouhollah nabatiGraph theory concepts   complex networks presents-rouhollah nabati
Graph theory concepts complex networks presents-rouhollah nabati
nabati2.8K 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 representation por DEEPIKA T
Graph representationGraph representation
Graph representation
DEEPIKA T45 vistas
Graphs (Models & Terminology) por zunaira saleem
Graphs (Models & Terminology)Graphs (Models & Terminology)
Graphs (Models & Terminology)
zunaira saleem129 vistas

Último

"Running students' code in isolation. The hard way", Yurii Holiuk por
"Running students' code in isolation. The hard way", Yurii Holiuk "Running students' code in isolation. The hard way", Yurii Holiuk
"Running students' code in isolation. The hard way", Yurii Holiuk Fwdays
17 vistas34 diapositivas
Mini-Track: Challenges to Network Automation Adoption por
Mini-Track: Challenges to Network Automation AdoptionMini-Track: Challenges to Network Automation Adoption
Mini-Track: Challenges to Network Automation AdoptionNetwork Automation Forum
13 vistas27 diapositivas
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... por
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...James Anderson
92 vistas32 diapositivas
virtual reality.pptx por
virtual reality.pptxvirtual reality.pptx
virtual reality.pptxG036GaikwadSnehal
14 vistas15 diapositivas
Business Analyst Series 2023 - Week 3 Session 5 por
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5DianaGray10
300 vistas20 diapositivas
Data Integrity for Banking and Financial Services por
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial ServicesPrecisely
25 vistas26 diapositivas

Último(20)

"Running students' code in isolation. The hard way", Yurii Holiuk por Fwdays
"Running students' code in isolation. The hard way", Yurii Holiuk "Running students' code in isolation. The hard way", Yurii Holiuk
"Running students' code in isolation. The hard way", Yurii Holiuk
Fwdays17 vistas
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N... por James Anderson
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
GDG Cloud Southlake 28 Brad Taylor and Shawn Augenstein Old Problems in the N...
James Anderson92 vistas
Business Analyst Series 2023 - Week 3 Session 5 por DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10300 vistas
Data Integrity for Banking and Financial Services por Precisely
Data Integrity for Banking and Financial ServicesData Integrity for Banking and Financial Services
Data Integrity for Banking and Financial Services
Precisely25 vistas
SAP Automation Using Bar Code and FIORI.pdf por Virendra Rai, PMP
SAP Automation Using Bar Code and FIORI.pdfSAP Automation Using Bar Code and FIORI.pdf
SAP Automation Using Bar Code and FIORI.pdf
Virendra Rai, PMP23 vistas
PharoJS - Zürich Smalltalk Group Meetup November 2023 por Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi132 vistas
Case Study Copenhagen Energy and Business Central.pdf por Aitana
Case Study Copenhagen Energy and Business Central.pdfCase Study Copenhagen Energy and Business Central.pdf
Case Study Copenhagen Energy and Business Central.pdf
Aitana16 vistas
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 por IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
6g - REPORT.pdf por Liveplex
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdf
Liveplex10 vistas
Powerful Google developer tools for immediate impact! (2023-24) por wesley chun
Powerful Google developer tools for immediate impact! (2023-24)Powerful Google developer tools for immediate impact! (2023-24)
Powerful Google developer tools for immediate impact! (2023-24)
wesley chun10 vistas
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... por Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker40 vistas
Future of AR - Facebook Presentation por ssuserb54b561
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
ssuserb54b56115 vistas

Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf

  • 1. Graph (I) Bruce Nan Email: xiaomingnan@gmail.com
  • 2. Seven Bridges of Königsberg  The Seven Bridges of Königsberg is a notable historical problem in mathematics. The problem was to find a walk through the city that would cross each bridge once and only once. The islands could not be reached by any route other than the bridges, and every bridge must have been crossed completely every time.
  • 3. Euler’s Analysis  During any walk in the graph, the number of times one enters a non- terminal vertex equals the number of times one leaves it.  If every bridge is traversed exactly once it follows that for each land mass (except possibly for the ones chosen for the start and finish), the number of bridges touching that land mass is even.  However, all the four land masses in the original problem are touched by an odd number of bridges (one is touched by 5 bridges and the other three by 3). Since at most two land masses can serve as the endpoints of a putative walk, the existence of a walk traversing each bridge once leads to a contradiction. C A D B
  • 4. Eulerian path  In graph theory, an Eulerian trail is a trail in a graph which visits every edge exactly once. Similarly, an Eulerian circuit or Eulerian cycle is a Eulerian trail which starts and ends on the same vertex.
  • 5. What is a 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. Edges are sometimes referred to as arcs.  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)}
  • 6. Applications  electronic circuits  networks (roads, flights, communications) CS16 LAX JFK LAX DFW STL HNL FTL
  • 7. Directed Vs. Undirected Graph  An undirected graph is one in which the pair of vertices in a edge is unordered, (v0, v1) = (v1,v0)  A directed graph is one in which each edge is a directed pair of vertices, <v0, v1> != <v1,v0>
  • 8. Terminology: Adjacent  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
  • 9. Degree of a Vertex  The degree of a vertex is the number of edges incident to that vertex  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 e di n = − ∑ ( ) / 0 1 2 Why? Since adjacent vertices each count the adjoining edge, it will be counted twice
  • 10. Examples 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 3 3 3
  • 11. Path  path: sequence of vertices v1,v2,. . .vk such that consecutive vertices vi and vi+1 are adjacent. The length of such a path is the number of edges on the path, which is equal to k-1. We allow a path from a vertex to itself; if this path contains no edges, then the path lenght is 0. 3 3 3 3 2 a b c d e a b c d e a b e d c b e d c
  • 12.  simple path: 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 a c d a a b c d e
  • 13. More Terminology  An undirected graph is connected if there is a path from every vertex to every other vertex.  A directed graph with this property is called strongly connected.
  • 14. More Terminology  subgraph: subset of vertices and edges forming a graph  connected component: maximal connected subgraph. E.g., the graph below has 3 connected components.
  • 15. Examples 0 0 1 2 3 1 2 0 1 2 3 (i) (ii) (iii) (iv) (a) Some of the subgraph of G1 0 0 1 0 1 2 0 1 2 (i) (ii) (iii) (iv) (b) Some of the subgraph of G3 0 1 2 3 G1 0 1 2 G3
  • 16. Tree and Forests  tree - connected graph without cycles  forest - collection of trees tree forest tree tree tree
  • 17. Examples V1 V2 V3 V4 V5 Tree V1 V2 V3 V4 V5 V1 V2 V3 V4 V5 V6 V7 Forest V1 V2 V3 V4 V5 V6 V7
  • 18. Connectivity  Let n = #vertices, and m = #edges  A complete graph: one in which all pairs of vertices are adjacent  How many total edges in a complete graph?  Each of the n vertices is incident to n-1 edges, however, we would have counted each edge twice! Therefore, intuitively, m = n(n -1)/2.  Therefore, if a graph is not complete, m < n(n -1)/2 n = 5 m = (5 ∗ 4)/2 = 10
  • 19. More Connectivity n = #vertices m = #edges  For a tree m = n - 1 n = 5 m = 4 If m < n - 1, G is not connected n = 5 m = 3
  • 20. How to store a Graph?  Adjacent Matrix  Adjacent Lists
  • 21. Adjacent Matrix  Let G=(V,E) be a graph with n vertices.  The adjacency matrix of G is a two-dimensional n by n array, say adj_mat  If the edge (vi, vj) is in E(G), adj_mat[i][j]=1  If there is no such edge in E(G), adj_mat[i][j]=0  The adjacency matrix for an undirected graph is symmetric; the adjacency matrix for a digraph need not be symmetric
  • 22. Examples for Adjacency Matrix 0 1 1 1 1 0 1 1 1 1 0 1 1 1 1 0             0 1 0 1 0 0 0 1 0           0 1 1 0 0 0 0 0 1 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0                           G1 G2 G4 0 1 2 3 0 1 2 1 0 2 3 4 5 6 7 symmetric
  • 23. More Adjacent Matrix  How to get the degree of vertex i? V1 V3 V4 V2 V1 V2 V3 V4 vertex= 0 1 0 1 1 0 1 1 0 1 0 0 1 1 0 0 arc= V1 V2 V3 V4 V1 V2 V3 V4 The number of non-zero data in ith row
  • 24. More Adjacent Matrix How to ensure if there is edge on vi and vj? V1 V3 V4 V2 V1 V2 V3 V4 vertex= 0 1 0 1 1 0 1 1 0 1 0 0 1 1 0 0 arc= V1 V2 V3 V4 V1 V2 V3 V4 Test whether arc[i][j] is 1
  • 25. More Adjacent Matrix V1 V3 V4 V2 V1 V2 V3 V4 vertex= 0 1 0 1 1 0 1 1 0 1 0 0 1 1 0 0 arc= V1 V2 V3 V4 V1 V2 V3 V4 How to find all adjacent vertices of vi? Traverse all ith row elements, if arc[i][j] is 1, vj is the adjacent vetex of vi
  • 26. Digraph Adjacent Matrix V1 V2 V3 V4 V1 V2 V3 V4 vertex= 0 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 arc= V1 V2 V3 V4 V1 V2 V3 V4 How to find the out degree of vi? sum all elements on ith row
  • 27. Digraph Adjacent Matrix How to find the in degree of vi? sum all elements on ith column V1 V2 V3 V4 V1 V2 V3 V4 vertex= 0 1 1 0 0 0 0 0 0 0 0 1 1 0 0 0 arc= V1 V2 V3 V4 V1 V2 V3 V4
  • 28. More Adjacent Matrix  From the adjacency matrix, to determine the connection of vertices is easy  The degree of a vertex is  For a digraph (= directed graph), the row sum is the out_degree, while the column sum is the in_degree ind vi A j i j n ( ) [ , ] = = − ∑ 0 1 adj mat i j j n _ [ ][ ] = − ∑ 0 1 outd vi A i j j n ( ) [ , ] = = − ∑ 0 1
  • 29. Create Adjacent Matrix buildGraph(int a[ ], int n, int e) { vertexNum=n; arcNum=e; for (i=0; i<vertexNum; i++) vertex[i]=a[i]; for (i=0; i<vertexNum; i++) //initialization for (j=0; j<vertexNum; j++) arc[i][j]=0; for (k=0; k<arcNum; k++) //get each edge { cin>>i>>j; //the vertices of the edge arc[i][j]=1; arc[j][i]=1; //adjacency } }
  • 30. Practice Time  Implement following functions  Given a graph, create the adjacent matrix  Insert edges between u and v  Delete edge between u and v  Output the degree of u  Output all the adjacent vertices of u
  • 31. Adjacency Lists  The space complexity of Adjacent Matrix?  Idea for Adjacency List:  For each vertex vi, using a list to store all adjacent vertices with vi, which is referred as vi’s edge list  Implementation  Vector array
  • 32. 0 1 2 3 0 1 2 0 1 2 3 4 5 6 7 1 2 3 0 2 3 0 1 3 0 1 2 G1 1 0 2 G3 1 2 0 3 0 3 1 2 5 4 6 5 7 6 G4 0 1 2 3 0 1 2 1 0 2 3 4 5 6 7 An undirected graph with n vertices and e edges ==> n head nodes and 2e list node
  • 33. More Adjacency List degree of a vertex in an undirected graph –# of nodes in adjacency list # of edges in a graph –determined in O(n+e) out-degree of a vertex in a directed graph –# of nodes in its adjacency list in-degree of a vertex in a directed graph –traverse the whole data structure
  • 34. Graph Traversal  Problem: Search for a certain node or traverse all nodes in the graph  Depth First Search  Once a possible path is found, continue the search until the end of the path  Breadth First Search  Start several paths at a time, and advance in each one step at a time  Topological Sorting
  • 35. Graph Traversal  Both graph traversal procedures share one fundamental idea, namely, that it is necessary to mark the vertices we have seen before so we don’t try to explore them again. Otherwise we get trapped in a maze and can’t find our way out.  BFS and DFS differ only in the order in which they explore vertices.
  • 36. Breadth-First Search (BFS)  A Breadth-First Search (BFS) traverses a connected component of a graph, and in doing so defines a spanning tree with several useful properties.  The starting vertex s has level 0, and, as in DFS, defines that point as an “anchor.”  In the first round, the string is unrolled the length of one edge, and all of the edges that are only one edge away from the anchor are visited.  These edges are placed into level 1  In the second round, all the new edges that can be reached by unrolling the string 2 edges are visited and placed in level 2.  This continues until every vertex has been assigned a level.  The label of any vertex v corresponds to the length of the shortest path from s to v.
  • 37. BFS - A Graphical Representation M N O P I J K L E F G H A B C D 0 M N O P I J K L E F G H A B C D 0 1 M N O P I J K L E F G H A B C D 0 1 2 3 M N O P I J K L E F G H A C D B 0 1 2
  • 38. V1 V3 V2 V4 V5 V6 V7 V8 Result: V1 V1
  • 39. V1 V3 V2 V4 V5 V6 V7 V8 V1 V2 V2 V3 V3 Result:
  • 40. V1 V3 V2 V4 V5 V6 V7 V8 V1 V2 V3 V3 V4 V4 V5 V5 Result:
  • 41. V1 V3 V2 V4 V5 V6 V7 V8 V1 V2 V3 V4 V4 V5 V5 V6 V6 V7 V7 Result:
  • 42. V1 V3 V2 V4 V5 V6 V7 V8 V1 V2 V3 V4 V5 V5 V6 V6 V7 V7 V8 V8 Result:
  • 43. Code – BFS Using Adjacent Matrix template <class T> void MGraph::BFSTraverse(int v) { front=rear=-1; //Assuming no overflow cout<<vertex[v]; visited[v]=1; Q[++rear]=v; while (front!=rear) { v=Q[++front]; for (j=0; j<vertexNum; j++) if (arc[v][j]==1 && visited[j]==0 ) { cout<<vertex[j]; visited[j]=1; Q[++rear]=j; } } }
  • 44. Code – BFS Using Adjacent List template <class T> void ALGraph::BFSTraverse(int v) { front=rear=-1; cout<<adjlist[v].vertex; visited[v]=1; Q[++rear]=v; while (front!=rear) { v=Q[++front]; p=adjlist[v].firstedge; while (p!=NULL) { j= p->adjvex; if (visited[j]==0) { cout<<adjlist[j].vertex; visited[j]=1; Q[++rear]=j; } p=p->next; } } }
  • 45. BFS Usage  Finding a path In a maze, how to find a path from the start to the end using least steps?  Exploiting traversal