0% found this document useful (0 votes)
8 views42 pages

5A-Graphs1 _ Updated

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views42 pages

5A-Graphs1 _ Updated

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 42

5.

Graphs
Part 1

Data Structures and Algorithms in Java 1/36


2
Objectives
• Graph Introduction
• Graph definition
• Shortest Paths
– Deep First Traversal
– Breath first traverse
– Floyd algorithm
– Dijsktra algorithm

Data Structures and Algorithms in Java 2/36


Graph Introduction
3
A graph include :
+ Vertices
+ Edges(between two vertices)
Graphs have applications in:
+ domains
+ Including mapping
+ Transportation
+ Computer networks
+ Electrical engineering

Data Structures and Algorithms in Java 3/36


Graph definition
4
A graph is a pair (V,E):
+ V : vertices
+ E : edges

Data Structures and Algorithms in Java 4/36


Graph Terminology
5 • Edges directed or undirected.
+ An edge (u,v) call directed if (u,v) ordered,u preceding v.
+ An edge (u,v) call undirected if (u,v) not ordered.
Graph undirected is graph If all the edges undirected graph.

Note: an undirected can be converted a directed graph by replacing every


undirected edge (u,v) by the pair of directed edges (u,v) and (v,u).

Data Structures and Algorithms in Java 5/36


Graph Terminology - 5

01/21/25 Data Structures and Algorithms in Java 6/36


Graph Terminology
7 • If remove vertices from graph and no way from a to
b, then the graph is split into two subgraphs, called:
+ articulation points
+ cut-vertices
• If an edge split into two subgraphs, called:
+ bridge
+cut-edge
• Connected subgraphs with no articulation points or
bridges are called blocks
We can use depth first traverse to check
the connectivity of a graph
Data Structures and Algorithms in Java 7/36
01/21/25 Data Structures and Algorithms in Java 8/36
Graph Examples
9
Single Weighted
undirected graph
graph

It has no multiple
A directed graph
edges and no loops
with multiple edges

An undirected graph
with loops
An undirected graph
with multiple edges

Data Structures and Algorithms in Java 9/36


Graph Terminology
10 • A complete graph is a graph where every pair of vertices is
connected by an edge.
• A simple complete graph on n vertices has n vertices and n(n-1)/2
edges, and is denoted by Kn
simple: just One
multiple: many

• A graph G'=(V', E') is a subgraph of another graph G=(V, E) iff V

Data Structures and Algorithms in Java 10/36


Directed graph
Undirected
graph

01/21/25 Data Structures and Algorithms in Java 11/36


adjacent vertices

incident edges

01/21/25 Data Structures and Algorithms in Java 12/36


01/21/25 Data Structures and Algorithms in Java 13/36
Graph applications
14
• Electronic circuits
• Transportation
networks
• Computer networks
• Database
– Entity-relationship diagram

Data Structures and Algorithms in Java 14/36


Graph Representation – 1
15
(Adjacency list)

Graph representations.
A graph (a) can be represented as
(b–c) an adjacency list.
Data Structures and Algorithms in Java 15/36
Graph Representation – 2
16
(Adjacency matrix)

Graph represented by an adjacency matrix

Data Structures and Algorithms in Java 16/36


Graph Representation – 3
(Incident matrix)
A vertex is said to be incident to an edge if the edge is connected to the vertex.

Graph represented by incident matrix

Data Structures and Algorithms in Java 17/36


Graph Traversals
Breadth-first Search
18

Data Structures and Algorithms in Java 18/36


Breadth-first Search Algorithm
Search a graph (directed or not) in breadth first, this is done by using
19 a queue where the vertices found are stored.
BFS(Graph G)
{ all vertices of G are first painted white
the graph root is painted gray and put in a queue
while the queue is not empty
{ a vertex u is removed from the queue
for all white successors v of u
{ v is painted gray
v is added to the queue
}
u is painted black
}
}
Data Structures and Algorithms in Java 19/36
Breadth-first Search code
// bread first traverse from vertex k
20
void breadthFirst(int k)
{MyQueue q = new MyQueue();int i,h;
boolean [] enqueued = new boolean[n];
for(i=0;i<n;i++) enqueued[i]=false;
q.enqueue(new Integer(k));enqueued[k]=true;
while(!q.isEmpty())
{h=Integer.parseInt((q.dequeue()).toString().trim());
visit(h);
for(i=0;i<n;i++)
if((!enqueued[i]) && a[h][i]>0)
{q.enqueue(new Integer(i));
enqueued[i] = true;
}
}
System.out.println();
}
Data Structures and Algorithms in Java 20/36
Depth-first Search Example

Data Structures and Algorithms in Java 21/36


Depth-First Search algorithm
DFS-visit (Graph G, Vertex u)
{ the vertex u is painted gray
for all white successors v of u
{ dfs-visit(G, v)
We use stack for DFS
}
DFS on a graph with n vertices and
u is painted black m edges takes O(n + m ) time
}
DFS (Graph G)
{ all vertices of G are first painted white
DFS-visit(G, root of G)
}

Data Structures and Algorithms in Java 22/36


01/21/25 Data Structures and Algorithms in Java 23/36
Depth-First Traverse code
void visit(int i)
{System.out.print(" " + v[i]);
}
void depthFirst(boolean visited[], int i)
{visit(i);visited[i] = true;
int j;
for(j=0;j<n;j++)
if(a[i][j]>0 && (!visited[j]))
depthFirst(visited,j);
}
void depthFirst(int k)
{int i; boolean [] visited = new boolean[20];
for(i=0;i<n;i++) visited[i]=false;
depthFirst(visited,k);
for(i=0;i<n;i++)
if(!visited[i])
depthFirst(visited,i);
System.out.println();
}
Data Structures and Algorithms in Java 24/36
Shortest Path problem
25

• The problem: find the shortest path between a pair of vertices of a


graph
• The graph: may contain negative edges but no negative cycles
• A representation: a weighted matrix where
W(i,j) = 0 if i=j.
W(i,j) =  if there is no edge between i and j.
W(i,j) = weight of the edge (i,j)

Data Structures and Algorithms in Java 25/36


Dijkstra's Algorithm - 1
26
• Apply the greedy-method and “weighted” breadth-first search.
• Apply the greedy method to the single-source, shortest-path
problem
 Dijkstra’s algorithm.

Data Structures and Algorithms in Java 26/36


Dijkstra's Algorithm
Example
Find the shortest path from (1) to (3) ?

01/21/25 Data Structures and Algorithms in Java 27/36


Step 1:
• Start with begin point (1), make a table same as below
• Update all weights of vertices that have direct edge
with (1)
• Rest of vertices that don’t have direct edge with (1) will
be ∞

Step The set 2 3 4 5


0 AE 5,A ∞ 9,A 1,A

01/21/25 Data Structures and Algorithms in Java 28/36


Step 2:
• we prioritize to inspect the current shortest path is go (1)
 (5).
• From (5), find all of direct path, then calculate sum of
weight follow fomular:
• total weight = weight (dictionary starts -> priority vertex)
+ weight (priority point -> point adjacent to priority point)
• Then compare them with value in the table, if less then
weight of the corresponding path, update.
Step 1: Inspect C=5

Step The set B-2 C-3 D-4 E-5


0 AE 5,A ∞ 9,A 1,A
1 AED 5,A ∞ 3,E

01/21/25 Data Structures and Algorithms in Java 29/36


Step 3:
• Do the same thing with the rest until the table left only 1
weight and that is the shortest path from (1)  (3) = 7

Step 2: Inspect C=4

Step The set B-2 C-3 D-4 E-5


0 AE 5,A ∞ 9,A 1,A
1 AED 5,A ∞ 3,E
2 AEDC 5A 9,D
3 ABC 7,B

01/21/25 Data Structures and Algorithms in Java 30/36


• The side weights must be non-negative numbers.

• we can see that: the shortest path from vertex 1 to vertex 4 will be road
1-> 3-> 4.
• Dijkstra : 5  False

01/21/25 Data Structures and Algorithms in Java 31/36


2
3 5

1 3

4 6
4

• If (1) – (2) – (3) is the shortest path from (1) – (3): weight = 8.
 (1,2) also be the shortest path from (1) to (2) and (2,3) also be the shortest path
from (2) to (3)

01/21/25 Data Structures and Algorithms in Java 32/36


Summary of Dijkstra's Algorithm:
STEP 1:
•Start with begin point (1), make a table same as below
•Update all weights of vertices that have direct edge with (1)
•Rest of vertices that don’t have direct edge with (1) will be ∞
STEP 2
•we prioritize to inspect the current shortest path is go (1)  (5).
•From (5), find all of direct path, then calculate sum of weight follow fomular:
•total weight = weight (dictionary starts -> priority vertex) + weight (priority point -> point
adjacent to priority point)
•Then compare them with value in the table, if less then weight of the corresponding path,
update.
STEP 3:
•Do the same thing with the rest until the table left only 1 weight and that is the shortest
path from (1)  (3)

01/21/25 Data Structures and Algorithms in Java 33/36


Floyd Algorithm
34
All pairs shortest path
• The problem: find the shortest path between every pair of
vertices of a graph
• The graph: may contain negative edges but no negative cycles
1. D = W // initialize D array to W [ ]
2. P = 0 // initialize P array to [0]
3. for k = 1 to n
4. do for i = 1 to n
5. do for j = 1 to n
6. if (D[ i, j ] > D[ i, k ] + D[ k, j ] )
7. then { D[ i, j ] = D[ i, k ] + D[ k, j ]
8. P[ i, j ] = P[k,j];
} Complexity O(|V|3)
Data Structures and Algorithms in Java 34/36
Floyd Algorithm example (cont.)
Example
Find the shortest path between any pair of vertices of graph?

Data Structures and Algorithms in Java 35/36


Step 1:
• Create 2D matrix in beginning
• Fill the Matrix with the weight of every pair of
vertices:
If 2 vertices don’t have the direct path, weight = ∞

01/21/25 Data Structures and Algorithms in Java 36/36


Step 2:
• Inspect all of vertices of graph, one by one.
• With vertex A, find all pairs of vertices have path through A, then calculate weight of that path.
• After that compare with value in the matrix, if sum of weight less than value in matrix, then replace it.
Example:
Inspect vertex (1), we have pairs of vertices have path
through (1) is:

pair Weight
4 – 1- 5 10
4–1–2 14
2–1-5 6

01/21/25 Data Structures and Algorithms in Java 37/36


• Do the same thing, after all we get matrix.
• But the weight of each path we got could not be the smallest because the matrix change after each time
we update

01/21/25 Data Structures and Algorithms in Java 38/36


• So we need to inspect and update again and again, until there
no weight of each pair need to be updated. We get:

• With this matrix, we can get the shortest path of any pair of
vertices.
• Example:
– (2) – (4): 8
– (1) – (3): 7

01/21/25 Data Structures and Algorithms in Java 39/36


Summary of Floyd Algorithm :
STEP 1:
•Create 2D matrix in beginning
•Fill the Matrix with the weight of every pair of vertices:
If 2 vertices don’t have the direct path, weight = ∞
STEP 2:
•Inspect all of vertices of graph, one by one.
•With vertex A, find all pairs of vertices have path through A, then calculate weight of that path.
•After that compare with value in the matrix, if sum of weight less than value in matrix, then replace it.
STEP 3:
•Do the same thing, after all we get matrix.
•But the weight of each path we got could not be the smallest because the matrix change after each time
we update.
•So we need to inspect and update again and again, until there no weight of each pair need to be
updated. We get the final matrix that we can get the shortest path of any pair of vertices.

01/21/25 Data Structures and Algorithms in Java 40/36


Dijsktra Floyd-Warshall
No need to re-run
Algorithm (meaning
Lower cost Floyd-
POSITIVE inherited from mutual
Warshall Algorithm
path) Can be run with
negative weights.
Can't run with negative High cost per pair of
NEGATIVE
weights. vertices
COMPARE BETWEEN Dijsktra & Floyd-Warshall

01/21/25 Data Structures and Algorithms in Java 42/36


43
Summary
• Graph Introduction
• Graph definition
• Graph Terminology
• Graph applications
• Graph Representation
• Graph Traversals
• Shortest Paths
– Dijsktra algorithm
– Floyd algorithm

Data Structures and Algorithms in Java 43/36

You might also like