You are on page 1of 38

Graphs

Data Structures

Ching-Fang Hsu
Dept. of Computer Science and Information Engineering
National Cheng-Kung University
Definitions

 A graph G consists of two sets.


 The set of vertices
 V(G)
 Finite and nonempty
 The set of edges
 E(G)
 Possibly empty
 An undirected graph
 The pair of vertices representing an edge is
unordered.
2
0 0 0

Definitions (contd.) 1 2 1 2 1

3
3 4 5 6 2

 A directed graph (a) G1 (b) G2 (c) G3

 Each edge is represented as a directed pair of


vertices.
 Ex. The pair <u, v> represents an edge in which u is
the tail and v is the head.
 A complete graph
 A graph that has the maximum # of edges
 The maximum # of edges for a graph with |V| = n
 Undirected  n (n - 1)/2, directed  n (n - 1)

3
0 0 0

Definitions (contd.) 1 2 1 2 1

3
3 4 5 6 2

(a) G1 (b) G2 (c) G3



0 Given an0edge (u, v)E(G), then 0

 The vertices u and v are adjacent.


1 2 1 2 1 2
 The edge (u, v) is incident on vertices u and v.

(i)
A subgraph
(ii)
of G 3 3
(iii) (iv)
 A graph G such
(a) 一些that V(G)  V(G) and E(G)  E(G)
G 的子圖
1


0 A path from
0 u to v in a graph
0 G 0

 A sequence of vertices, u, i1, i2,  , ik, v, such that (u, i1),


1 1 1
(i1, i2),  , (ik, v) are edges in an undirected graph G.
2 2 2
(i) 4
(ii) (iii)
(iv)
(b) 一些 G3 的子圖
0 0 0

Definitions (contd.) 1 2 1 2 1

3
3 4 5 6 2

(a) G1 (b) G2 (c) G3

 The length of a path


 The number of edges on the path
 A simple path
 A path in which all vertices, except possibly the first
and the last, are distinct
 Ex. 0, 1, 3, 2 in G1
 A cycle
 A simple path in which the first and the last vertices
are the same
5
Definitions (contd.)

 Two vertices u and v are connected in an


undirected graph G if there is a path in G from u
to v.

6
Definitions (contd.)

 The degree of a vertex


 The number of edges incident to that vertex
 For a directed graph
 in-degree vs. out-degree

0 0 0

1 2 1 2 1

3
3 4 5 6 2

(a) G1 (b) G2 (c) G3

7
Graph Representation

 The most commonly used representations


 Adjacency matrices
 Adjacency lists

8
Graph Representation --
Adjacency Matrices
 A two-dimensional n  n array a
 a[i][j] = 1 iff the edge (i, j)  E(G); otherwise, a[i][j] = 0.
 The main advantage
 Determining the degree of a vertex i is a simple task.
n 1
 For an undirected graph: the sum of row i  a[i ][ j ]
j 0
 For a directed graph: the row sum  the out-degree
the column sum  the in-degree
 The main disadvantage
 All algorithms that need to examine all edges require (n2) time.
 n2 - n entries
 Not efficient for sparse graphs
9
adjLists data link
0 0 0
[0] 3 1 2 0

[1] 2 3 0 0

[2] Graph Representation --


1 3 0 0
1 2 1 2 1

Adjacency Lists
3
[3] 0 1 2 0 3 4 5 6 2

(a) G1 (b) G2 (c) G3


(a) G1

adjLists

[0]  One chain


1 0 for each vertex in G, instead of one

[1] row of the


2 adjacency
0 0 matrix H 0 1 4 H2

[2] 0
 The nodes in chain i represent the vertices
2 that are
1 5 6

adjLists
adjacent(b)from
G3
vertex i.
3 7
[0]  For an undirected
2 1 graph
0 with n vertices and e G4
[1]
edges, an
3
array of
0
size
0
n and 2e chain nodes
[2]
are required.
0 3 0

[3] 1 2 0

[4]
 Two fields
5 0
in a chain node
[5] 6 4 0

[6] 5 7 0

[7] 6 0 10

(c) G4
Graph Representation --
Weighted Edges
 A graph with weighted edges is called a
network.
 For an adjacency matrix
 Replace the 1 used to signify an edge with the weight
of the edge
 For adjacency lists and adjacency multilists
 A weight field is needed!

11
Elementary Graph Operations

 Given an undirected graph, G = (V, E), and a


vertex vV(G), visit all vertices reachable from v.
 Depth first search
 Breadth first search

12
Elementary Graph Operations
-- Depth First Search
 Assume that the start vertex is v.
public void dfs(int v) {
nodePointer w;
visited[v] = true;
System.out.println(v);
for(w = g[v]; w != null; w = w.getLink()) {
if(!visited[w.getVertex()]) {
dfs(w.getVertex());
}
}
}
 Time complexity
 Adjacency lists: (e)
 An adjacency matrix: (n2)
13
Elementary Graph Operations
-- Breadth First Search
 Assume that the start vertex is v.
 Visit each of the vertices on v’s adjacency list
 When all the vertices on v’s adjacency list have been
visited, visit all the unvisited vertices adjacent to the
first vertex on v’s adjacency list.

 A dynamically linked queue is exploited.


 Time complexity
 Adjacency lists: (e)
 An adjacency matrix: (n2)
14
public void bfs(int v) {
nodePointer w = new nodePointer();
System.out.println(v); Not an empty queue
visited[v] = true;
addq(v);
while(front != null && front.getVertex() >= 0) {
v = deleteq();
for(w=g[v]; w.getVertex() >= 0 && w != null; w=w.getLink()) {
if(!visited[w.getVertex()]) {
System.out.println(w.getVertex());There is at least one
w is unvisited addq(w.getVertex()); remaining node w in
visited[w.getVertex()] = true; v’s adjacency list
}
} Line up for w’s neighbor nodes
} Visitng w
}

15
Elementary Graph Operations
-- Spanning Trees
 What is a spanning tree?
 Any tree that consists solely of edges in graph G and
that includes all the vertices in G
 A minimal subgraph, G, of G such that V(G) = V(G)
and G is connected
 Given that |V(G)| = n, a spanning tree has n - 1 edges
 How to create a spanning tree?
 A depth first spanning tree vs. a breadth first
spanning tree

16
0 0

1 2 1 2

3 4 5 6 3 4 5 6

7 7

(a) DFS(0) 生成樹 (a) BFS(0) 生成樹


0

1 2

3 4 5 6

(a)

adjLists
[0] 1 2 0

[1] 0 3 4 0

[2] 0 5 6 0

[3] 1 7 0

[4] 1 7 0

[5] 2 7 0

[6] 2 7 0

[7] 3 4 5 6
17
(b)
Minimum Cost Spanning Trees

 The cost of a spanning tree of a weighted


undirected graph
 The sum of the costs (weights) of the edges in the
spanning tree
 A minimum cost spanning tree is a spanning
tree of least cost.
 How to obtain a minimum cost spanning tree?
 Based on a design strategy called the greedy method

18
Minimum Cost Spanning Trees
(contd.)
 Construct an optimal solution in stages
 At each stage, make a decision that is the best (using some
criterion) at this time
 Make sure that the decision will result in a feasible solution
 The selection of an item at each stage is typically based on
either a least cost (e.g., minimum spanning trees problem) or
a highest profit criterion.
 A feasible solution must satisfy the following
constraints
 Only edges within the graph can be used.
 Exactly (n – 1) edges can be used.
 Edges that would produce a cycle may not be used.
19
Minimum Cost Spanning Trees
(contd.)
 Two well-known algorithms
 Kruskal’s algorithm
 Prim’s algorithm

20
Minimum Cost Spanning Trees
-- Kruskal’s Algorithm
 Build a minimum cost spanning tree T by
adding edges to T one at a time.
 Step 1: Select the edges in nondecreasing order of
their cost
 Maintain the edges in E as a sorted sequential list for
more efficient processing
 Time complexity of sorting the edges in E: (e log e)
 A min heap is ideally suited!
 Step 2: Check if an edge forms a cycle with the
edges that are already in T if it is added to T
 Exactly (n – 1) edges will be selected 21
public ArrayList<edge> Kruskal(ArrayList<edge> e, int graphSize) {
ArrayList<edge> tempEdgeList = e;
edge tempEdge = new edge();
Minimum Cost Spanning Trees
int[] nodeGroup = new int[graphSize];

--Collections.sort(tempEdgeList);
Kruskal’s Algorithm (contd.)
t = new ArrayList<edge>();
for(int i=0; i<graphSize; i++) {
nodeGroup[i]=i;
 }The total time complexity is (e log e).
while(t.size() < graphSize-1 && tempEdgeList.size() > 0) {
tempEdge = tempEdgeList.get(0);
tempEdgeList.remove(0);
if(findGroup(tempEdge.getNode1(), nodeGroup) !=

findGroup(tempEdge.getNode2(), nodeGroup)) {
t.add(tempEdge);
nodeGroup[tempEdge.getNode2()] = tempEdge.getNode1();
}
}

if(t.size() < graphSize-1) {


System.out.println("No spanning tree");
}
22
return t;
}
0 28 0 0
1 1 1
10 10
14 16
Minimum Cost Spanning Trees
5
24
6 2 5 6 2 5 6 2

-- Kruskal’s Algorithm (contd.)


25
4
18 12
22 3
4
3
4
3

(a) (b) (c)

0 0 0
1 1 1
10 10 10
14 14 16
5 6 2 5 6 2 5 6 2

12 12 12
4 4 4
3 3 3

(d) (e) (f)

0 0
1 1
10 10
14 16 14 16
5 6 2 5 6 2

12 25 12
4 4
22 3 22 3

(g) (h) 23
Minimum Cost Spanning Trees
-- Prim’s Algorithm
 Build a minimum cost spanning tree T by
adding edges to T one at a time
 At each stage, the set of selected edges forms a tree.
 cf. Kruskal’s (a forest at each stage)
 Step 1: Begin with a tree T containing a single vertex
 Any vertex in the original graph
 Step 2: Add a least cost edge (u, v) to T such that T 
{(u, v)} is also a tree.
 Exactly one of u or v is in T
 Time complexity: (n2)
24
Minimum Cost Spanning Trees
-- Prim’s Algorithm

25
Minimum Cost Spanning Trees
-- Prim’s Algorithm
0 0 0
1 1 1
10 10 10

5 6 2 5 6 2 5 6 2

25 25
4 4 4
3 3 22 3

(a) (b) (c)

0 0 0
1 1 1
10 10 10
16 14 16
5 6 2 5 6 2 5 6 2

25 12 25 12 25 12
4 4 4
22 3 22 3 22 3

(d) (e) (f)


26
Shortest Paths -- Single Source All
Destinations : Nonnegative Edge Costs

 Givens
 A directed graph, G = (V, E)
 A weighting function, w(e), w(e) > 0 eE
 A source vertex, v0
 Let v0S, SV and the shortest paths of all vertices in
S have been found. wS, distance[w] is the length of
the shortest path starting from v0, going through
vertices only in S, and ending in w.
 The goal
 Determine a shortest path from v0 to each of the
remaining vertices of G
27
Shortest Paths -- Single Source All
Destinations : Nonnegative Edge Costs
(contd.)


wS
v0

u
S
distance[w]  min (the length of a path pv0 ,w , where vS for all v pv0 ,w and v  v0 and w )
vS, distance[v] = min (distance[v], distance[u] + cost[u][v])
28
Shortest Paths -- Single Source All
Destinations : Nonnegative Edge
Costs (contd.)
 Dijkstra’s algorithm
 Initial: S = {v0} and iV, distance[i] = cost[v0][i]

 w( u, v  )  u, v  E

cost[u ][v ]    u, v  E and u  v
0 uv

 Step 1: Find uS whose distance[u] is the smallest among
distance[i],  iS, and set S = S  {u}
 Step 2: vS, if distance[v] > distance[u] + cost[u][v], set
distance[v] = distance[u] + cost[u][v]
 If the shortest paths of all vertices have been found
already, stop; otherwise, go to Step 1. 29
public void shortestPath(int v, int[][] cost, int[] distance, int n,
boolean[] found)
{
int i, u, w;

for(i = 0; i < n; i++) {


found[i] = false;
distance[i] = cost[v][i];
Initialization
}
found[v] = true;
distance[v] = 0;
for(i = 0; i < n-2; i++) {
u = choose(distance, n, found);
Step 1
found[u] = true;
for(w = 0; w < n; w++) {
if(!found[w]) {
if(distance[u] + cost[u][w] < distance[w]) {
distance[w] = distance[u] + cost[u][w];
Step 2
}
}
}
}
30
}
public int choose(int[] distance, int n, boolean[] found)
{
int i, min, minpos;
min = Integer.MAX_VALUE;
minpos = -1;
for(i = 0; i < n; i++) {
if(distance[i] < min && !found[i]) {
min = distance[i];
minpos = i;
}
}
return minpos;
}

31
Activity on Vertex (AOV)
Networks
 Many projects can be divided into several
subprojects called activities.
 Precedence relations among activities
 Can be represented as a directed graph
 Definition (AOV networks)
 An AOV network is a directed graph G in which the
vertices represent activities and the edges represent
precedence relations between activities.

32
C1, C2, C4, C5,
C3, C6, C8, C7,
C10, C13, C12,
C14, C15, C11, C9

C4, C5, C2, C1,


C6, C3, C8, C15,
C7, C9, C10, C11,
C12, C13, C14

33
Activity on Vertex (AOV)
Networks (contd.)
 Definition (Predecessors)
 Vertex i in an AOV network G is a predecessor of
vertex j iff there is a directed path from i to j. Vertex i
is an immediate predecessor of vertex j iff <i, j> is an
edge in G.
 Definition (Successors)
 If i is a predecessor of j, then j is a successor of i. If i
is an immediate predecessor of j, then j is an
immediate successor of i.

34
Activity on Vertex (AOV)
Networks (contd.)
 If an AOV network represents a feasible project,
the precedence relations must be both
transitive and irreflexive.
 A relation  is transitive iff for all triples i, j, k, i  j and j
 k  i  k. A relation  is irreflexive on a set S if i  i is
false iS.
 We can show that a precedence relation is
irreflexive by proving that the network is a
directed acyclic graph (dag).

35
Activity on Vertex (AOV)
Networks (contd.)
 Definition (Topological order)
 A topological order is a linear ordering of the vertices
of a graph such that, for any two vertices, i, j, if i is a
predecessor of j in the network then i precedes j in
the linear ordering.
 An algorithm for topological sorting

36
Activity on Vertex (AOV)
Networks (contd.)

37
38

You might also like