08 Graphs 3 Labs
08 Graphs 3 Labs
Graphs
Introduction to Graphs
Graphs 2
Introduction to Graphs…
Examples:
Graphs 3
Learning Outcomes
Graphs 4
Learning Outcomes
Graphs 6
1- Definitions
vertex
vertex’s
label
edge
• Graph Classification:
– Based on direction of edges:
– Based on number of edges connection
two vertices.
– Based on whether or not edges are
evaluated. An edge may have proper data
(a number).
Mix graph: a graph having multiple
properties.
Graphs 9
1- Definitions…
Graphs 10
1- Definitions…
• Classification based on number of
edges between vertices
– Simple graph: two distinct vertices in un-directed
graph can be join atmost ONE edge
– Multigraph is a graph in which two vertices can be
joined by multiple edges
– Pseudograph is a multigraph which allows for loops at
one vertex.
Graphs 11
1- Definitions…
Graphs 12
1- Definitions…
Graphs 13
1- Definitions…
Path and circuit/circle
• A path is a group of consecutive edges.
• A circuit or circle is a closed path.
Graphs 14
1- Definitions…
Connectivity:
A graph is connected if and only if there
exist a path between two arbitrary different
vertices.
- If a graph is not connected, it is a combination
of at least two connection components.
Graphs 15
1- Definitions…
Connectivity…
- Articulation point/cut vertex(điểm khớp/đỉnh cắt)
- Cut edge (cạnh cắt) / Bridge (cầu)
A special vetex or edge in a graph having
special property that when it is removed, it
causes the graph unconnected.
Graphs 16
2- Graph Representation
Graphs 17
2- Graph Representation…
Representing a graph using a matrix:
Graphs 18
2- Graph Representation…
Some graphs using adjacency matrices:
Graphs 19
2- Graph Representation…
Representing a graph using a matrix:
Graphs 20
2- Graph Representation…
Representing a graph using an adjacency list:
Adjacency
list of a
vertex
Vertex list
Graphs 21
3- Graph Traversals
Graph traversal:
• An operation which will visit all vertices, each
vertex will be done only one time O(n).
• Traversals on a graph are similar as those are
introduced in the chapter Trees.
– Breadth-First Traversal (Breadth-First Search- BFS)
– Depth- First Traversal (Depth-First Search- DFS)
Graphs 22
3- Graph Traversals…
1 6 7 9
2
3
4 8
aefgibchd
Graphs 23
3- Graph Traversals…
num(v) is a positive
breadthFirstSearch() // using a queue integer which
describes the visited
for all vertices v num(v) = 0; // reset visited orders
order of the vertex v
order = 1; // order begin from 1
while there is a vertex v such that num(v) is 0 // Visiting all vertices
num(v) = order++;
enqueue (v)
while queue is not empty
v=dequeue();
for all vertices u adjacent to v // considering all adjacent vertices of v
if num(u) is 0 {
num(u) = order++;
enqueue(u);
}
Graphs 24
3- Graph Traversals…
Breadth First Search: Walking through the algorithm:
Result Queue
(a,1)
(a,1) (e,2),(f,3),(g,4),(i,5)
a efgi (a,1),(e,2) (f,3),(g,4),(i,5)
b g
(a,1),(e,2),(f3) (i,5)
c h
d h (a,1),(e,2),(f3),(g,4), (i,5),(b,6)
e afi (a,1),(e,2),(f3),(g,4),(i,5) (b,6)
f aei
(a,1),(e,2),(f3),(g,4),(i,5),(b,6) (c,7)
g ab
h cd (a,1),(e,2),(f3),(g,4),(i,5),(b,6),(c,7) (h,8)
i aef
(a,1),(e,2),(f3),(g,4),(i,5),(b,6),(c,7),(h,8) (d,9)
(a,1),(e,2),(f3),(g,4),(i,5),(b,6),(c,7),(h,8),(d,9)
Graphs 25
3- Graph Traversals…
Breadth First Search: Walking through the algorithm:
(For taking quiz)
Queue
aefgi
aefgI
aefgi
aefgib
aefgib
aefgibc
Một đỉnh đã được đưa vào hàng đợi rồi thì
aefgibch
gạch ngang (đánh dấu đã xử lý) aefgibchd
aefgibchd
Graphs 26
3- Graph Traversals…
Graphs 27
3- Graph Traversals…
G1 G2
Result:
1, …….. 1, ……..
Graphs 28
3- Graph Traversals…
Depth-First Search algorithm:
Each vertex v is visited and then each
unvisited vertex adjacent to v is visited.
1
6 7 9
2
3
5
8
4
Graphs 29
3- Graph Traversals…
Depth-first search algorithm: each vertex v is visited
and then each unvisited vertex adjacent to v is
visited
DFS (Vertex u) // Recursive algorithm
num(u) = order++; // i: visiting order
for all vertices v adjacent to u
if (num(v) is 0) // v is not traversed yet
attach edge uv to edges; // update result
DFS(v); // recursive traversing down
depthFirstSearch()
for all vertices v num(v) = 0;
edges = null; // Initiate the traverse result
order = 1;
while there is a vertex v such that num(v) is 0 DFS(v);
output edges;
Graphs 30
3- Graph Traversals…
An example of application of the depthFirstSearch()
Graphs 31
3- Graph Traversals…
Graphs 32
3-Graph Traversals…
G1 G2
Graphs 33
4- Cycle Detection
Graphs 34
Lab 1- Demo 1: Traversing a Graph
(Using Adjacency Matrix)
Objectives:
- Traverse a
simple
undirected
matrix- Graph_Matrix: class for a graph.
MyQueue: Class for a queue
based graph TestTraverser: Tester
- Output
traversal
results to Output files
monitor and
files. Input file
Graphs 35
Demo 1: Traversing a Graph
Input:
Graphs 36
Demo 1: Traversing a Graph
MyQueue.java
Graphs 37
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 38
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 39
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 40
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 41
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 42
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 43
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 44
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 45
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 46
Demo 1: Traversing a Graph
Graph_Matrix.java
Graphs 47
Demo 1: Traversing a Graph
TestTraverser.java
Graphs 48
Demo 1: Traversing a Graph
TestTraverser.java
Graphs 49
Demo 1: Traversing a Graph
TestTraverser.java
Graphs 50
Demo 1: Traversing a Graph
TestTraverser.java
Graphs 51
5- Shortest Paths
• Weight of an edge:
– A real number which depends on specific
problem.
– It is positive but it may be negative in some
cases.
• Road map: road length (meter)
Shortest
• Aero map: fly length/ cost ($) Paths are
• Computer network: bandwidth (bit/sec) basic
• Drainage net: water flow (m /s)
3
requirement
• Electricity grid: load power (watt) in Graph
• .... theory
• It may be a multiple-variable function
Graphs 52
5- Shortest Paths…
• Label: considered values are applied to
each vertex. In this Dijkstra, introduced,
Label(v) = {cost(v), predecessor(v)}
• To get shortest path between two vertices, each
vertex must be chosen to scan for evaluating. In
each pass, only one vertex is chosen to scan.
• Classification:
– Label-setting methods: In each pass through the
vertices still to be processed, one vertex is set to a
value that remains unchanged to the end of the
execution, the Dijkstra algorithm is an example.
– Label-correcting methods: Allow for the changing of
any label during application of the method
Graphs 53
5- Shortest Paths…
Algorithms:
Main algorithm:
• Dijkstra — weight of edge >=0
Algorithms should be referenced:
• Bellman-Ford — weight of edge may be negative.
• A*: Using heuristics to improve performance
• Floyd-Warshall — Determine shortest path for all pair of
vertices.
• Johnson — Determine shortest path for all pair of
vertices. It can be more efficient than Floyd-Warshall on
a sparse graph.
Attention: Each algorithm has it’s own purpose and a specific graph type.
Graphs 54
5- Shortest Paths…
GenericShortestPathAlgorithm (weighted simple digraph,
vertex first) Dijkstra
for all vertices v cost(v) = toBeChecked= all vertices
cost(first)=0;
initialize toBeChecked; // set of vertices will be checked
while (toBeChecked is not empty)
v= a vertex in toBeChecked; // depending on specific algorithm
remove v from toBeChecked;
Ford
for all vertices u adjacent to v Examine edges instead of vertices
if cost(u) > cost(v) + weight(v,u))
cost(u) = cost(v) + weight(v,u));
O(|V|2) predecessor(u)= v;
Add u to toBeChecked if it is not there;
Graphs 55
5- Shortest Paths…
DJ ShortestPathAlgorithm (weighted simple digraph, vertex first)
for all vertices v {
marked(v) = false; cost(v) = ; predecessor (v) = null;
}
cost(first) = 0;
v = first;
while (v != null) {
marked (v) = true;
for all vertices u adjacent to v {
if (marked (u)=false AND (cost(u) > cost(v) + weight(v,u))) {
cost(u) = cost(v) + weight(v, u));
predecessor(u)= v;
}
}
v= the minimum cost vertex in non-marked vertices;
}
Graphs 56
5- Shortest Paths…
V = infinity
5,a- 12,j
8,e-
0,null-
An execution of DijkstraAlgorithm
(1) Độ dài đường đi ngắn nhất từ d sang i =?
(2) Đường đi ngắn nhất từ d sang i là đường nào?
(3) Sau bước lặp thứ 3 của thuật toán DJ, độ dài đường đi ngắn nhất từ d đến i =? 10
Graphs 57
5- Shortest Paths…
Graphs 58
Lab 2- Demo 2: SP Dijkstra Algorithm
Dijkstra
Algorithm Impl.
Input
output file
Graphs 59
Demo 2: SP Dijkstra Algorithm
DJ_Finder.java
Graphs 60
Demo 2: SP Dijkstra Algorithm
DJ_Finder.java
Graphs 61
Demo 2: SP Dijkstra Algorithm
DJ_Finder.java
Graphs 62
Demo 2: SP Dijkstra Algorithm
DJ_Finder.java
Graphs 63
Demo 2: SP Dijkstra Algorithm
DJ_Finder.java
Graphs 64
Demo 2: SP Dijkstra Algorithm
DJ_Test.java
Graphs 65
Demo 2: SP Dijkstra Algorithm
Graphs 66
6- Spanning Trees- Cây phủ
Subgraph: G’ (V’, E’) is called as a subgraph of the
graph G(V, E) if and only if V’ is a subset of V and E’ is
a subset of E.
Spanning Tree: G’ (V’, E’) is called as a spanning tree
of subgraph of the graph G(V, E) if and only if V’=V and
E’ is a subset of E and G’ is a tree (connected, having
no cycle).
A graph
may have
some
spanning
trees.
Graphs 68
6- Spanning Trees…
Graphs 69
6- Spanning Trees…
• Minimum spanning tree-
Kruskal algorithm:
• Lấy cạnh có trọng số bé mà
không tạo thành vòng.
Graphs 70
6- Spanning Trees…
• Read by yourself
• Minimum spanning tree- Dijkstra algorithm:
– Input: weighted connected, undirected graph
– Output: minimum spanning tree
• tree = null;
• edges = an unsorted sequence of all edges of graph ;
• for j=1 to |E|
- add ej to tree;
- if there is a cycle in tree, remove an edge with
maximum weight from this only cycle;
Graphs 71
6- Spanning Trees…
• Read by yourself
• Minimum spanning tree- Dijkstra
algorithm:
Edges are
choosen in
natural order
of edge
abels
Graphs 72
6- Spanning Trees…
• Read by yourself
• Minimum spanning tree- Prim-Jarnik algorithm:
Graphs 73
6- Spanning Trees…
74
Read by yourself
Prim-Jarnik Algorithm demo
A spanning tree of
graph (a) found
with Prim’s
algorithm starting
with the vertex 0.
The vertices are
selected in the
following order:
0, 1, 7, 6, 5, 2, 8,
3, 4
74/30
Graphs
7- Euler Cycles
Graphs 75
7- Euler Cycles…
C
Is it possible to start at some
A location, travel across all the
D bridges without crossing any
bridge twice, and return to
B the same starting point?
C
Kneiphof island on Pregel river
and 7 bridges built in 18-th
century in Königsberg town A D
(Kaliningrad).
Graphs 76
7- Euler Cycles…
Necessary and sufficient conditions for Euler cycles/ Euler path
Undirected graph
Theorem 1: A connected multigraph has an Euler cycle if
and only if each of its vertices has even degree.
Theorem 2: A connected multigraph has an Euler path
but Euler cycle if and only if it has exactly two odd degree
vertices.
Which of
graphs have
Euler cyles/
Euler path?
Graphs 77
7- Euler Cycles…
Directed graph
1,2
Which of
graphs have
Euler cyles/
Euler path?
Graphs 78
7- Euler Cycles…
Algorithm Euler for a graph having Euler cycle.
Main Idea: Splicing all sub-cycles
Graphs 79
7- Euler Cycles…
Algorithm Euler(G)
Input: Connected graph G with all vertices having even degrees
Output: Euler cycle
Construct a cycle in G
Remove all the edges of cycle from G to get subgraph H
while H has edges
find a non-isolated vertex v that is both in cycle and in H
//the existence of such a vertex is guaranteed by G’s connectivity
construct subcycle in H
splice subcycle into cycle at v
remove all the edges of subcycle from H
return cycle
Graphs 80
7- Euler Cycles…
Algorithm for finding an Euler cycle from
the vertex X using stack
Algorithm Euler(G, start) Chuyển các
//Input: Connected graph G with all vertices having even degrees chu trình
//Output: Euler cycle
con vào
declare a stack S of vertices which will be examined stack, giảm
declare empty array E (which will contain Euler cycle) bậc mỗi
push the vertex start to S
while(S is not empty) { đỉnh của
u= the vertex on the top of the stack S các chu
if (u is isolated) then remove it from the stack and put it to E trình này 2
else
v= an arbitrary vertex which is adjacent to u, đơn vị cho
push v to S đến khi bậc
Remove edges (u, v) and (v,u) from the graph của đỉnh
}
Vertices in E form a Euler cycle of the graph bằng 0.
Graphs 81
Lab 3- Demo 3: Euler Cycle
Finding an Euler cycle using stack
A C E G
B D F H
Implementations
Input/
output files
Graphs 82
Euler_Graph.java Demo 3: Euler Cycle
Finding an Euler cycle using stack
Graphs 83
Euler_Graph.java Demo 3: Euler Cycle
Finding an Euler cycle using stack
Graphs 84
Euler_Graph.java Demo 3: Euler Cycle
Finding an Euler cycle using stack
Graphs 85
Euler_Graph.java Demo 3: Euler Cycle
Finding an Euler cycle using stack
Graphs 86
Euler_Graph.java Demo 3: Euler Cycle
Finding an Euler cycle using stack
Graphs 87
Euler_Graph_Test.java
Demo 3: Euler Cycle
Finding an Euler cycle using stack
Graphs 88
Euler_Graph_Test.java
Demo 3: Euler Cycle
Finding an Euler cycle using stack
Graphs 89
8- Hamilton Cycles
Hamilton cycle: visits every vertex of the graph
exactly once before returning, as the last step, to the
starting vertex.
Examples:
7 vertices:
6! options
A C B E G F D A
A A A A A A
B B B B B B O(n!) AI is needed
C C C C C C
D D D D D D
E E E E E E
F F F F F F
G G G G G G
Graphs 91
8- Hamilton Cycles…
A graph can have some Hamilton cycles.
List all Hamilton’s cycles using Backtracking
Graphs 92
8- Hamilton Cycles…
Finding Hamilton’s cycles using Backtracking
(Exhausted Searching – vét cạn- dò tìm cho đến
cùng)
Given the graph G = (V,E) and X is a vertex of G. Suppose
there exists at least one Hamilton Cycle for the graph. The
following is a backtracking algorithm for finding one Hamilton
cycle from the vertex X:
declare an empty array H (which will contain Hamilton cycle)
(1) Put the vertex X to H
(2) Check if H is a Hamilton cycle then stop, else go to (3)
(3) Consider the last vertex Y in H, if there is/are vertex(es)
adjacent to Y, select an adjacent vertex Z and put it to H. If
there no adjacent vertex, remove Y from H and denote it as a
bad selection (so you do not select it in the same way again).
Go to (2). O(n!) AI is needed
Graphs 93
9- Graph Coloring Problem
Graphs 95
9- Graph Coloring Problem…
• Sequential coloring establishes the sequence of
vertices and a sequence of colors before coloring
them, and then color the next vertex with the
lowest number possible
sequentialColoringAlgorithm(graph = (V, E))
put vertices in a certain order vP1, vP2, . vpi . . , vPv ;
put colors in a certain order c1, c2, . . . , ck;
for i = 1 to |V|
j=the smallest index of color that does not appear in any neighbor of vPi;
color(vPi) = cj;
Complexity: O(|V|2)
Graphs 96
Summary
Graphs 99