Sunteți pe pagina 1din 58

Week 7 : Graph

Data Structures & Algorithm


Analysis

1
Lecture Outline

 Graph
 Graph terminology
 Graph representation

 Graph traversal
 Depth-first traversal
 Breadth-first traversal

 Topological Ordering
 Shortest Path

2
Learning Objective
 To describe the characteristics of the graph including its
vertices, edges and path,
 To differentiate between directed and undirected graph,
 To describe and differentiate between adjacency matrix
and list,
 To identify how to traverse nodes using breadth and
depth first search,
 To identify how to find topological order in a graph, and
 To find shortest path for weighted or un-weighted graph

3
Road Maps

Nodes

Edges

A portion of a road map


(The vertices are drawn as circle, the edges are drawn using lines)
4
Graph Terminology
 A graph is a data structure that consists of a set
of vertices and a set of edges between pairs of
vertices
 Vertices or nodes are connected by edges.
 Edges represent paths or connections between
the vertices
 The set of vertices and the set of edges must both
be finite and neither one be empty
  A graph is a collection of distinct vertices and
distinct edges
 Edges can be directed or undirected
 When it has directed edges it is called a digraph
5
Visual Representation of Graphs
 Vertices are represented as points or
labeled circles and edges are
represented as lines joining the vertices

6
Graph Terminology (cont’s)
 Hubbard & Anita (2004),
Graph is a pair G = (V, E) are sets and
every element of E is a two-element subset
of V
V – Vertices E – Edges

 Two vertices are adjacent if there is an


edge connecting them
 The size of graph is the number of its
vertices.
7
Size of graph

SE

UK DE
CZ

 Size of graph = 8 FR CH AT

IT

8
Subgraph
SE

UK DE DE
CZ CZ

FR CH AT FR CH AT

IT IT
G G’
 A subgraph is a portion of a graph that itself is a graph
 If G = (V, E) is a graph and G’ = (V’, E’) where V’  V and E’  E,
then, G’ is a subgraph of G.
 Graph G’ is a sub graph of the graph G. Two vertices (SE, UK) and
two edges have been removed. 9
Directed and Undirected Graphs
 The edges of a graph are directed if the
existence of an edge from A to B does not
necessarily guarantee that there is a path
in both directions
 A graph with directed edges
is called a directed graph.
The edges are drawn using arrows.
 A graph with undirected edges is an
undirected graph or simply a graph. The
edges are drawn using lines.
10
Paths
 A sequence of edges that connect two
vertices in a graph
 The length of a path is the number of edges
that it comprises.
 In a directed graph the direction of the
edges must be considered
 called a directed path
 A cycle is a path that begins and ends at
same vertex
 Simple path : if the path does not pass through
any vertex more than once
 A graph with no cycles is acyclic
11
Paths and Cycles

12
Weights
 The edges in a graph may have values
associated with them known as their
weights
 A graph with weighted edges is known as a
weighted graph
 A weighted graph has values on its edges
 Weights or costs
 A path in a weighted graph also has weight
or cost
 The sum of the edge weights
 Examples of weights
 Miles between nodes on a map
 Driving time between nodes
 Taxi cost between node locations 13
Weights

14
Category of Graph

 Graph has two categories:


 Directed Graph or digraph
 Every edge has an arrow

 Has cycle vertex or acyclic vertex

 Undirected Graph
 Every edge has no arrows

 Has cycle vertex

15
Directed Graph (Digraph)

G1 = (V1, E1)

V1 = { a, b, c, d, e, f}
E1 = {(a,d), (a,e), (d,c), (e,b), (b,a), (b,c), (c,f), (f,f) }

e a d

b f

16
Undirected Graph
G2 = (V2, E2)

V2 = {a, b, c, d}
E2 = { {a,b}, {a,c}, {b,c}, {c,d} }
or
E2 = { (a,b), (b,a), (a,c), (c,a), (b,c), (c,b), (c,d), (d,c) }

Attention: a b
{a,b} = (a,b), (b,a)

c d
17
Connected Graphs

 A connected graph
 Has a path between every pair of
distinct vertices
 A complete graph
 Has an edge between every pair of
distinct vertices
 A disconnected graph
 Not connected

18
Connected Graphs

Undirected graphs 19
Course Prerequisites

The prerequisite structure for a selection of


courses as a directed graph without cycles.

20
Trees
 All trees are graphs
 But not all graphs are trees

 A tree is a connected graph without cycles


 Traversals
 Preorder, inorder, postorder traversals are examples of
depth-first traversal
 Level-order traversal of a tree is an example of
breadth-first traversal
 Visit a node
 For a tree: process the node's data

 For a graph: mark the node as visited

21
Airline Routes
 Note the graph with two subgraphs
 Each subgraph connected
 Entire graph disconnected

A graph that represents the routes that airline flies


22
Adjacent Vertices

 Two vertices are adjacent in an


undirected graph if they are joined by an
edge
 Sometimes adjacent vertices are called
neighbors

Vertex A is adjacent to B, or Vertex B adjacent from A,


but B is not adjacent to A.
23
Graph Representation

 To write programs that process and


manipulate graph, the graph must be
stored in computer memory.
 A graph can be represented (in computer
memory) in 2 commonly used ways:
 Adjacency matrices
 Adjacency lists

24
The Adjacency Matrix
 Is a 2 dimensional n  n matrix.
 For a graph with n vertices, has n rows and
n columns
 Each row, each column corresponds to a vertex
in the graph
 Numbered 0 through n – 1
 Element aij indicates whether an edge exists
between vertex i and vertex j
 Elements of the matrix contain
 Boolean for unweighted graph
 Edge weights for weighted graph

25
The Adjacency Matrix

(a) A directed graph and


(b) its adjacency matrix.

26
The Adjacency Matrix – directed graph

e a d

b f

a b c d e f

a 0 0 0 1 1 0
A1 = b 1 0 1 0 0 0
c 0 0 0 0 0 1
d 0 0 1 0 0 0
e 0 1 0 0 0 0
f 0 0 0 0 0 1
27
The Adjacency Matrix – undirected graph

a b

a b c d
c d
a 0 1 1 0
A2 = b 1 0 1 0
c 1 1 0 1
d 0 0 1 0

28
The Adjacency Matrix

 Adjacency matrix uses fixed amount of


space
 Depends on number of vertices
 Does not depend on number of edges
 Typically the matrix will be sparse
 Presence of an edge between two vertices
can be known immediately
 All neighbors of a vertex found by
scanning entire row for that vertex

29
The Adjacency List

 Represents only edges that originate


from the vertex
 Space not reserved for edges that do
not exist
 Uses less memory than corresponding
adjacency matrix
 Thus more often used than adjacency
matrix

30
The Adjacency List

Adjacency lists
for the directed
graph

31
The Adjacency List – directed graph

a
d e
b
a c

c e a d
f
d
c c
e b f
b
f
f

32
The Adjacency List – undirected graph

a b
a b c

b a c c d

c a b d

d c

33
Graph Traversal
 The most common graph traversal
algorithm:
 Breadth- First Traversal
 It follows a path that explores an entire level before
moving to next level
 The traversal uses one queue to hold the unvisited
neighbors of a vertex, and another queue to maintain
traversal order.
 Depth- First Traversal
 It follows a path that goes as deeply into the graph as
possible before following other graph
 The traversal uses a stack to hold the unvisited
neighbors of a vertex, and a queue to maintain
traversal order 34
Breadth-First Traversal
A trace of a breadth-
first traversal for a
directed graph,
beginning at vertex
A.

35
Breadth-First Traversal

1 a

2 3 4
b c d

5
e 6 h

7 f g 8

36
Breadth-First Traversal (Trees)

The visitation order of two traversals;


(a) depth first; (b) breadth first.

37
Algorithm for Breadth-First Traversal

38
Example of a Breadth-First Traversal

39
Example for Breadth-First Traversal

40
Depth-First Traversal

 Visits a vertex, then


 A neighbor of the vertex,
 A neighbor of the neighbor,

 Etc.

 Advance as possible from the


original vertex
 Then back up by one vertex
 Considers the next neighbor

41
Depth-First Traversal

1 a

2 6 8
b c d

3
e 7 h

4 f g 5
42
Depth-First Traversal

A trace of a depth-first
traversal beginning at
vertex A of the
directed graph

43
Topological Order
 A graph can have several different
topological orders (linear ordering)
 Possible only for a directed graph without
cycles
 A graph that has no cycle:
 There is exists a vertex u in G such that u has
no predecessor
 There is exists a vertex v in G such that v has
no successor
 In a topological order
 Vertex a precedes vertex b whenever
 A directed edge exists from a to b
 Can be implemented using either the dept
first traversal or the breadth first traversal. 44
Topological
Order

Three
topological
orders.

45
Topological Order
 Algorithm for Breadth First Topological Ordering
 Create an array predCount, and initialize it so
that predCount[i] is the number of
predecessors of the vertex vi.
 Initialize the queue, say queue, to all those
vertices vk so that predCount[k] is zero.
 While the queue is not empty:
 Remove the front element, u, of the queue
 Put u in the next available position, say
topologyOrder[topIndex], and increment
topIndex
 For all the immediate successors w of u:
 Decrement the predecessor count of w by 1.
 If the predecessor count of w is zero, add w to queue
46
Topological Order

An impossible prerequisite structure for three courses


as a directed graph with a cycle.

47
Shortest Path in a Graph
 A graph can have several different paths
between the same two vertices.
 In unweighted, the shortest path is a
path with shortest length or a path that
has fewest edges.
 In weighted, the shortest path is a path
that has the smallest edge-weight sum.

48
Shortest Path in an Unweighted Graph

 Shortest path between two given


vertices
 Has the shortest length (fewest edges).
 Algorithm based on breadth-first
traversal
 If several paths have the same
shortest path, the algorithm will find
only one of them.

49
Shortest Path in an Unweighted Graph

Fig (a) an unweighted graph and


(b) the possible paths from vertex A to vertex H.
50
Shortest Path in an Unweighted Graph

The graph in (a) after the shortest-path algorithm


has traversed from vertex A to vertex H

51
Shortest Path in an Unweighted Graph

Finding the shortest path from vertex A to vertex H in


the unweighted graph in Fig.(a).
52
Shortest Path in an Weighted Graph

 Shortest path between two given vertices


 Smallest edge-weight sum
 Algorithm based on breadth-first
traversal
 Several paths in a weighted graph might
have same minimum edge-weight sum
 Algorithm given by text finds only one of
these paths

53
Shortest Path in an Weighted Graph

Fig.(a) A weighted graph and


(b) the possible paths from vertex A to vertex H.

54
Shortest Path in an Weighted Graph

Finding the
cheapest path
from vertex A to
vertex H in the
weighted graph in
Fig (a).

55
Shortest Path in an Weighted Graph

After finding the cheapest path from vertex A to


vertex H.

56
Applications of Graph

o Computer networking (in the connection of


the internet).
o Transportation (in road and flight network/
routes)
o Mapping (in geographic information
system.)
o Electrical engineering (in logic circuit)

57
References
 Data Structures and Abstractions with Java . Authors: Frank
M. Carrano & Walter Savitch . Chapter 29 & 30

 Data Structures & Other Objects Using Java. Author: Michael


Main Chapter 14

 Data Structures with Java. Author: John R. Hubbard & Anita


Huray. Chapter 16

58

S-ar putea să vă placă și