Graphs Graphs: Definition Directed vs. Undirected

Directed vs. Undirected Edges
Graphs
• An edge (u, v ) connects two vertices u and v in the graph.
Readings: Chapter 14
• Edge (u, v ) is directed if it indicates the direction of travel.
u
v
Vertex u is the origin; Vertex v is the destination.
(u, v ) 6= (v , u)
CSE214: Computer Science II
Spring 2016
• An edge (u, v ) is undirected if it does not indicate a direction.
u
C HEN -W EI WANG
v
(u, v ) = (v , u)
An undirected edge (u, v ) is equivalent to two directed edges
(u, v ) and (v , u).
2
Graphs
3 of 55
Graph –
most general data structure - consists of set of vertices (V)
and a set of edges (E) that connect vertices – G = {V, E}
• vertices can also be referred to as nodes
Graphs:
Definition
• in Graph ADT, both vertices and edges are Positions, i.e they
store elements (e.g. v.element(), e.element())
A graph G = (V , E) represents relationships that exist
between pairs of objects.
B
vertex =
city
computer
Web-page
task
• An edge (u, u), either directed or undirected, is called a
self-edge (or a self-loop ).
u
E
A
C
Self vs. Parallel Edges
D
• Edges that have the same two end vertices are parallel edges
edge =
road
cable
hyperlink
transition state
F
A set V of objects: vertices (nodes)
A collection E of connections between objects: edges (arcs)
WWW, activity charts
Application• Each
– road
edge ismaps,
a pair of computer
vertices from Vnetworks,
.
e.g., G = ({A, B, C, D, E, F }, {(A, B), (A, C), (A, E), (C, D), (D, E), (B, F )})
(Are two
connected? What is the shortest path between them? etc. )
2 ofpoints
55
or multiple edges .
u
v
e.g., In a flight network graph, there are more than one airlines
flying between two Seoul and Vancouver.
• A simple graph has no self-loops and parallel edges.
4 of 55
Vertices
Directed vs. Undirected Graphs
5
Given an edge (u, v ):
Graphs: Types of Vertices
• Vertices u and v are its two End vertices ( Endpoints ).
• The two end vertices u and v is said to be adjacent .
vertices
End Vertices
(Endpoints)
of an
– two
• Edge
(u, v ) is incident
on Edge
the two end
vertices
u and v .joined by the edge
• When edge (u, v ) is directed:
• in a directed
u is origin and v is destination
is origin and
Edge (u, v ) is an outgoing edge of the origin u
• In a directed graph , all edges are directed.
e.g., dependency graphs (inheritance relationships, method
calls, etc.)
• In an undirected graph , all edges are undirected.
edge, the first endpoint e.g., Subway map of Incheon line
the other is destination • In a mixed graph , some edges directed; some undirected.
Adjacent Vertices
– endpoints of the same edge
Edge (u, v ) is an incoming edge of the destination u
• Theon
degree
of a vertex
v is theisnumber
of edges
incident endpoints
on v .
one of
the edge’s
Edge Incident
Vertex
– vertex
Outgoing Edges
of a Vertex – directed edges that originate at the vertex
5 of 55
e.g., A city map has street intersections as vertices and streets
as edges: each street may be one-way (a directed edge) or
both-way (an undirected edge).
7 of 55
Incoming Edges of a Vertex – directed edges that terminated at the vertex
Degree of a Vertex – deg(v) = number of incoming and outgoing edges of v
= number of edges incident on v
Exercise (1)
Directed Graph Example (1): A Flight Network
n
r
• Edges incident on vertex A?
• Degree of vertex A?
6 of 55
NW
35
SFO
UA
• End vertices of edge m?
• Outgoing edges of vertex A?
• Incoming edges of vertex A?
JFK
[A, B]
[m, o]
[q]
[m, o, q]
[3]
0
12
AA
13
DFW
LAX
AA 49
AA
5
AA 411
8 of 55
87
23
MIA
DL 247
C
D
DL 3
35
o
q
ORD
s
AA 903
p
BOS
7
A
F
E
UA 8
7
m
SW 45
B
Directed Graph Example (2): Class Inheritance
Undirected Graph Example (2): Co-authorship
Snoeyink
Garg
SmartPhone
Goldwasser
IOS
Android
Goodrich
IPhone6s
IPhone6sPlus
Samsung
Tamassia
Graph: Basic Propertie
Tollis
HTC
GalaxyS6Edge
GalaxyS6EdgePlus
HTCOneA9
∑d
graph with m
edges then
Property 1:VitterIf G is aPreparata
Chiang
HTCOneM9
v∈G
Proof
9 of 55
11 of 55
On the left-hand side, every undirected edge (u,v) i
by its endpoint u and once by its endpoint v.
1
∑ deg(v) = deg(v ) + deg(v
2
) + ... + de
v∈G
Undirected Graph Example (1): London Tube
Kensal
Rise
Willesden Junction
Brondesbury
Park
Queen’s Park
Kilburn Park
Maida Vale
Finchley Road
Swiss Cottage
Kilburn
High Road
Paddington
South
Hampstead
Marylebone
Edgware Road
Bayswater
Latimer Road
North
Acton
Shepherd’s
Bush Market
Goldhawk Road
Hammersmith
Turnham Stamford Ravenscourt
Park
Brook
Green
10 of 55
Notting
Hill Gate
Holland
Park
Wood Lane
Regent’s Park
Bond
Street
Queensway
Hyde Park Corner
Knightsbridge
Gloucester
Road
Barons
Court
1
Victoria
West
Kensington
Earl’s
Court
South
Kensington
Sloane
Square
Green Park
v∈G
Each directed edge (u,v) contributes once to indeg
⌃ degree(v ) = 2 · m
once
v 2 V to outdeg sum of its destination
Barbican
Holborn
Chancery Lane
Bank
Covent Garden
St. Paul’s
Cannon Street
Westminster
∑ indeg
Old Street
Piccadilly
Circus
St. James’s
Park
Proof
Farringdon
Leicester Square
Charing
Cross
Given a graph G = (V , E) with |E| = m edges:
Angel
Euston
Square
Moorgate
Tottenham
Court Road
Lancaster
Gate
High Street Kensington
Kensington
(Olympia)
Caledonian
Road &
Barnsbury
King’s Cross
St. Pancras
Russell
Square
Goodge
Street
Oxford
Circus
Marble Arch
Shepherd’s
Bush
Mornington
Crescent
Warren Street
1
Westbourne Park
Camden
Road
Camden Town
Baker Great Portland Euston
Street
Street
Edgware
Road
Ladbroke Grove
Chalk Farm
St. John’s Wood
Warwick
Avenue
Royal Oak
White
City
2
West Hampstead
Brondesbury
Kensal Green
East
Acton
Caledonian Road
Kilburn
Harlesden
Basic Properties of Graphs (1)
Property 2: If G is a directed graph, then
m
1
Blackfriars
Ri
Temple
Embankment
London
Bridge
p
o
q
Mansion House
F
E
A
Monument
n
B
C
r
s
D
Proof: Each edge (u, v ) contributes to degrees of both u and v .
12 of 55
m
A
B
o
q
C
1
∑ deg(v) = deg(v ) + deg(v
2
) + ... + deg(v n )
v∈G
Basic Properties of
Graphs= (2) outdeg(v) = m
indeg(v)
is a directed graph, then
∑
Paths and Cycles (1)
∑
v∈G
Given a graph G = (V , E):
• A path of G is a sequence of alternating vertices and edges,
which starts and ends at vertices:
v∈G
Given a directed graph G = (V , E):
ted edge (u,v) contributes once to indeg sum of its origin, and
⌃ in-degree(v ) = ⌃ out-degree(v )
tdeg sum of its destination
v 2V
v 2V
n
F
E
p
r
m
D
p
C
• A simple cycle of G is a cycle of G with distinct vertices
• Given two vertices u and v in G, vertex v is reachable from
D
r
8
and Cycles
(except
start Graphs:
and end).
Graphs:
Paths Paths
and Cycles
s
o
q
vi 2 V , 1  i  n, ej 2 E, 1  j < n
• A cycle of G is a path of G with same start and end vertices.
F
E
1 , en 1 , vn i
• A simple path of G is a path of G with distinct vertices.
n
B
A
s
hv1 , e1 , v2 , e2 , . . . , vn
vertex u if there exists a path of G such that its start vertex is u
end
vertex
v .vertices and
ofisalternating
vertices
and
edgesat– astarts
at a vertex
–andsequence
sequence
of alternating
edges
– starts
vertex
Path – Path
Vertex
v may
and
atbe
a reachable
vertex from vertex u via more than one paths.
Proof: Each directed edge (u, v ) contributes to the
and ends
at aends
vertex
Any
of
the
reachable
paths from u to v contains a cycle
7
out-degree of origin u and the in-degree of destination v .
)
An
infinite
number
of reachable paths from u to v .
Graphs: Basic Properties (cont.)Simple Simple
in the
path is distinct
– eachinvertex
13 of 55
each vertex
the path
is distinct
Path15 of–55Path
Property 3: In a simple undirected graph with n vertices and m edges
(no self-loops and parallel edges) the following must hold
n(n − 1)
m≤
2
with identical
end vertex
– path
path with
identical
start andstart
end and
vertex
Cycle –Cycle
max possible
number of edges in
a graph with n nodes
in the
cycle is distinct
– eachinvertex
each vertex
the cycle
is distinct
Simple Simple
Cycle –Cycle
Basic Properties ofProof
Graphs
Assume (3)
all n vertexes are mutually connected (case with max # of edges).
Paths and Cycles (2)
Such a graph is called complete.
Given simple, undirected graph G = (V , E) with n vertices and
2
3
n
m =|E|
deg(v
m edges (i.e., |V | = n and
= 1m):
in G ) + deg(v in G- {v } ) + deg(v in G- {v ,v } ) + .. + deg(v in G- {v ,v ,..,v } )
1
m
1
2
E
C
D
E
C
D
• Proof: Say V = {v1 , v2 , . . . , vn }
Maximum value of m is obtained when each vertex is connected to
all other n 1 vertices: n · (n 1)
Since G is undirected, for each pair of vertices vi and vj , we have
double-counted (vi , vj ) and (vj , vi ):
n·(n 1)
2
• G is a complete graph when m = n·(n2 1)
A
q
E
C
B
m
A
o
B
A
n
n-1
A
B
A
2
m
n(n - 1)
n·(n 1)
m = (n - 1) + (n - 2) + ... + 1 =
2
2
B
14 of 55
1
C
n
B
t o
q
F
E
p
E
r
C
s
D
F
p
t
r
s
D
m
n
B
m
oA
A
q
C
n
B
p
E
t
q
r
o
D
C
F
E
s
F
p
t
r
s
D
Path = (F, s,
D, t,= E,
Path
(F,p,s,F,D,n,t,B)
E, p, F, n, B)
Cycle = (E, Cycle
p, F, n,=B,
D,A,
s, o,
F, E,
p, t,
E)D, s, F, p, E)
(E,m,
p,A,
F, o,
n, E,
B,t,m,
DSimple Path = (C, q, A, o, E)
Simple Path = (C, q, A, o, E)
Simple Cycle
= (E, Cycle
t, D, r, =C,(E,
q, t,A,D,
o,r,E)C, q, A, o, E)
Simple
Vertex F is reachable from vertex A via:
• (A, m, B, n, F )
• (A, o, E, p, F )
• (A, o, E, t, D, s, F )
...
16 of 55
8
Graphs: Subgraphs
• undirected connected graph without cycles
• connected components of a forest are free trees
Subgraph – graph in G whose vertices and edges are subset of vertices
and edges of G
Spanning Tree – subgraph of G that contains all of G’s vertices a
Spanning Subgraph – subgraph in G that contains all the vertices of G
Subgraphs vs. Spanning Subgraphs
Connected Graph – for any two vertices there is a path between them
enough of its edges to form a tree
Forests vs. Trees
• in a graph with cycles there is more than one span
Given a graph G = (V , E):
• A forest is an undirected graph without cycles.
9
connected subgraphs
Connected Components
a Graph – maximal
0 = (V’, E’)ofsuch
• A subgraph of G is another
graph
G
that
Graphs: Subgraphs
B
F
m
V’ ✓ V and that E’ is a sub-collection of E.
E
s
A
e.g.,Subgraph
G1 = ({A,– B,
C, D, E, F }, {m, q, r })
o
graph in G whose vertices and edges are subset of vertices
and edges of G B
m
m B
F
E p
E
in G that contains allAthe vertices of G
Spanning Subgraph – subgraph
A
t
F
m
s
A
D
q two vertices D
there is a path between
Connected Graph – for any
C them
r
C
r
Spanning Subgraph =
subgraphs
Connected Components of aSubgraph
Graph =– maximal connected
• A spanning
subgraph of{A,GB, is
another
G0B,=
(V’,
such
= {A,
C, D,
E, F}E’)
U {m,
o, p, s, t, r}
C, D}
U {m, q, r} graph
that V’ = V and that E’ is a sub-collection of E.
e.g., G2 = ({A, B, C, D, E, F }, {m, p, s, t, r })
m
B
E
A
q
17 of 55
F
C
r
m
B
E
A
D
Subgraph =
{A, B, C, D} U {m, q, r}
p
t
C
r
F
m
s
A
D
Spanning Subgraph =
= {A, B, C, D, E, F} U {m, o, p, s, t, r}
n
B
E
F
p
o
C
r
D
Graph with 2
Connected Components
Connected Graph vs. Connected Components
Given a graph G = (V , E):
• G is connected if for any vertices of G, there is a path
between them.
e.g., Spanning subgraph G2 extended with the edge n, o, or q
• connected components are its maximal connected subgraphs.
e.g., How many connected components does the following
graph have?
n
B
E
q
F
p
o
C
r
Graph with 2
Connected Components
A
D
q
• There exists a pair of vertices that are not connected by a path
) The forest is not connected.
• A tree is a connected undirected graph without cycles, i.e., a
connected forest.
e.g., Add either edge (E, F ) or (E, D) to the above forest.
In order not to have a cycle, any two vertices is connected via
exactly one path.
19 of 55
Spanning Trees
1212 12
Graphs:
Forests
Trees
Graphs:
Forests
and
Trees
Forests
Trees
Given a graph Graphs:
G,
a spanning
treeand
ofand
its
is
a tree that contains
12 12
12
Graphs: Forests
Forestsand
andTrees
Trees
all its vertices. Graphs:
[ spanning
trees
]Forests and Trees
Example
2[spanning
Graphs:
spanning
trees
]
Example
2
[
trees
]
Example
2
In other words, a spanning tree of G is a connected spanning
spanning
] ] no cycles.
[ spanning
trees
Example
Example2 2[of
subgraph
G that trees
contains
trees
]
Example
2 [ spanning
BB B
BB B
FF F
FF F
EE E
BB
AA A
AA
FF
B E E DD D F
CC C E
A
DD
CC
D
C
BB
AA A
20 of 55
EE E
FF F
FF
B E E DD D F
CC C E
ASpanning
Tree
Spanning
Tree
Spanning
3 3D3D
C C Tree
D
CTree
Spanning
3 3
Spanning
Tree
AA
Answer: 3
B
E
F
p
s
o
C
D
Forest
Spanning Tree
In order not to have a cycle, any
two vertices can be connected via
at most one path.
A forest may or may not be connected.
D
BB B
18 of 55
C
m
BB
AA A
EE E
FF
B E E DD D F
CC C E
A
DD
Spanning
Tree
1
Spanning
Tree
Spanning
11
C C Tree
D
C
Spanning
Tree
1
Spanning Tree 1
AA
Spanning
Tree 1
B
BB
FF F
EE E
B
AA A B
FF
B E E DD D F
A A CC C
E
ASpanning
Tree
Spanning
Tree
Spanning
4 4D4D
C C Tree
D
C
Spanning
Tree
4 4
Spanning
Tree
BB B
AB
AA B
EE E
FF F
FF
B E E DD D F
A A CC C
E
A
DD
Spanning
Tree
2
Spanning
Tree
Spanning
Tree
22
CC
D
C
Spanning
Tree
2
Spanning Tree 2
Tree 2
B
BBSpanning
FF F
EE E
B
AA A B
FF
B E E DD D F
A A CC C
E
ASpanning
Tree
Tree
5 D5
Spanning
5D
CSpanning
C Tree
D
C Tree
Spanning
5 5
Spanning
Tree
Are
there
any
other
spanning
threes
besides
these?
Find
them!
Are
there
other
spanning
threes
besides
these?
Find
them!Tree 5
Are
there
any
other
spanning
threes
besides
Find
them!
Spanning
Tree
3 any
Spanning
Tree
4 these?
Spanning
Are
there
any
other
spanning
threes
besides
these?
them!
Are
there
any
other
spanning
threes
besides
these?Find
Find
them!
Are there any other spanning threes besides these? Find them!
Exercise (2)
Graphs in Java: Doubly-Linked Node and List
Given a graph
For each graph, we maintain two lists of vertices and edges.
public class DLNode<E> { /* Doubly-Linked Node */
private E element;
private DLNode<E> prev; private DLNode<E> next;
public DLNode(E e, DLNode<E> p, DLNode<E> n) { . . . }
/* setters and getters for prev and next */
}
Which one of the following is a spanning tree?
(a)
(b)
(c)
• (a) is a spanning subgraph but contains a cycle () not a tree).
• (b) is a tree but not spanning.
21 of 55
Basic Properties of Graphs (4)
class Vertex<V> {
private V element;
public Vertex(V element) { this.element = element; }
/* setter and getter for element */
}
We prove the case of G being a spanning tree via mathematical
induction on n:
• Base Cases: n = 1 ) m = 0, n = 2 ) m = 1, n = 3 ) m = 2
• Inductive Cases: Assume that a spanning tree has n vertices and
1 edges.
• When adding a new vertex v 0 into the existing graph, we may only
expand the existing spanning tree by connecting v 0 to exactly one of
the existing vertices; otherwise there will be a cycle.
• This makes the new spanning tree contains n + 1 vertices and n edges.
22 of 55
When G is a forest, it is not necessarily connected ) m  n
When G is connected, it might contain cycles ) m n 1
23 of 55
Graphs in Java: Vertex and Edge
Given G = (V , E) an undirected graph with |V | = n vertices
and |E| = m edges:
8
>m = n 1 if G is a spanning tree
<
m  n 1 if G is a forest
>
:
m n 1 if G is connected
n
public class DoublyLinkedList<E> {
int size;
private DLNode<E> header; private DLNode<E> trailer;
void remove (DLNode<E> node) {
DLNode<E> pred = node.getPrev();
DLNode<E> succ = node.getSucc();
pred.setNext(succ); succ.setPrev(pred);
node.setNext(null); node.setPrev(null);
size --;
}
}
class Edge<E, V> {
private E element;
private Vertex<V> origin;
private Vertex<V> dest;
public Edge(E element) { this.element = element; }
/* setters and getters for element, origin, and destination */
}
1
24 of 55
Graphs in Java: Interface (1)
public interface Graph<V,E> {
/* Number of vertices of the graph */
int numVertices();
/* Number of edges of the graph */
int numEdges();
/* Vertices of the graph */
Iterable<Vertex<V>> vertices();
/** Edges of the graph */
Iterable<Edge<E, V>> edges();
/* Number of edges leaving vertex v. */
int outDegree(Vertex<V> v);
/* Number of edges for which vertex v is the destination. */
int inDegree(Vertex<V> v);
Graphs in Java: Interface (3)
/* Inserts a new vertex, storing given element. */
Vertex<V> insertVertex(V element);
/* Inserts a new edge between vertices u and v,
* storing given element.
*/
Edge<E, V> insertEdge(Vertex<V> u, Vertex<V> v, E element);
/* Removes a vertex and all its incident edges from the graph. */
void removeVertex(Vertex<V> v);
/* Removes an edge from the graph. */
void removeEdge(Edge<E, V> e);
} /* end Graph */
int degree(Vertex<V> v);
25 of 55
Graphs in Java: Interface (2)
27 of 55
Graphs in Java: Edge List (1)
Each vertex and edge stores a reference to its position in the
list.
/* Edges for which vertex v is the origin. */
Iterable<Edge<E, V>> outgoingEdges(Vertex<V> v);
/* Edges for which vertex v is the destination. */
Iterable<Edge<E, V>> incomingEdges(Vertex<V> v);
/* The edge from u to v, or null if they are not adjacent. */
Edge<E, V> getEdge(Vertex<V> u, Vertex<V> v);
) O(1) deletion of the vertex or edge from the list.
class EdgeListVertex<V> extends Vertex<V> {
DLNode<Vertex<V>> vertextListPosition;
/* setter and getter for vertexListPosition */
}
class EdgeListEdge<E, V> extends Edge<E, V> {
DLNode<Edge<E, V>> edgeListPosition;
/* setter and getter for edgeListPosition */
}
26 of 55
28 of 55
Graphs in Java: Edge List (2)
Graphs in Java: Edge List (4)
int numVertices() {
return vertices.size();
}
class EdgeListGraph<V, E> implements Graph<V, E> {
private DoublyLinkedList< EdgeListVertex <V>> vertices;
Running Time?
private DoublyLinkedList< EdgeListEdge <E, V>> edges;
private boolean isDirected;
O(1)
Iterable<Vertex<V>> vertices {
ArrayList<Vertex<V>> vs = new ArrayList<>();
DLNode<Vertex<V>> current = vertices.first();
while(current != null) {
vs.add(current.getElement());
current = current.getNext();
}
return vs;
}
/* initialize an empty graph */
EdgeListGraph(boolean isDirected) {
vertices = new DoublyLinkedList<>();
edges = new DoublyLinkedList<>();
this.isDirected = isDirected;
}
19
1. Edge List Structure (cont.)
Running Time?
29 of 55
O(n)
31 of 55
Edge List Structure – the simples implementation of a graph
• each vertex / edge is represented by an object
• all vertices are stored in container V, all edges
are stored in container E
direct access from edges to the vertices they are
Graphs in Java: •Edge
List (3)
incident upon is provided – endVertices, origin,
destination, opposite run in O(1) time
• access to edges incident upon a given vertex is
inefficient – all edge objects must be inspected
V
D
A
r
o
B
A
q
p
o
B
p
C
D
q
Graphs in Java: Edge List (5)
Iterable<Edge<E, V>> outgoingEdges(Vertex<V> v) {
ArrayList<Edge<E, V>> oes = new ArrayList<>();
DLNode<Edge<E, V>> current = edges .first();
while(current != null) {
/* directed graph: add edge if v is the origin
* undirected graph: add edge if v is one of the end points
*/
if ( current.origin == v ||
( current.dest == v && !isDirected
oes.add(current.getElement());
r
)) {
}
current = current.getNext();
C
}
return oes;
E
}
30 of 55
Running Time?
O(m)
Exercise: Iterable<Edge<E, V>> incomingEdges(Vertex<V> v)
Exercise: int outDegree(Vertex<V> v)
32 of 55
Graphs in Java: Edge List (6)
Graphs in Java: Edge List (8)
Edge<E, V> getEdge(Vertex<V> u, Vertex<V> v); {
Edge<E, V> e = null;
DLNode<Edge<E, V>> cur = edges.first();
while(cur != null) {
/* directed graph: origin is u and destination is v
* undirected graph: order does not matter
*/
if ( cur.origin == u && cur.dest == v ||
( cur.dest == u && cur.dest == v && !isDirected
edge = cur;
)) {
}
cur = cur.getNext();
}
return edge;
void removeVertex(Vertex<V> v) {
vertices.remove(v.getVertexListPosition());
DLNode<Edge<E, V>> cur = edges .first();
while(cur != null) {
/* each edge that is incident on v should be removed */
if ( cur.origin == v || cur.dest == v ) {
edges.remove(cur);
}
cur = cur.getNext();
}
}
} /* end EdgeListGraph */
}
Running Time?
Running Time?
33 of 55
35 of 55
Graphs in Java: Edge List (7)
Graphs in Java: Adjacency List (1)
• Extends the edge list structure
• Each vertex v also stores a list of incident edges.
Vertex<V> insertVertex(V element) {
Vertex<V> v = new EdgeListVertex(element);
v.setVertexListPosition(vertices.addLast(v));
}
Edge<E, V> insertEdge(Vertex<V> u, Vertex<V> v, E element) {
EdgeListEdge<E, V> e = new EdgeListEdge<>(element, u, v);
e.setEdgeListPosition(edges.addLast(e));
}
Running Time?
Exercise: void removeEdge(Edge<E, V> e)
O(1)
) vertex-based methods such as outgoingEdges and
removeVertex takes O(dv ) rather than O(m)
• Each edge also stores references to its positions in the incident
edges lists of its two end vertices.
) O(1) deletion of the edge from the incident edges list.
class AdjacencyListVertex<V> extends EdgeListVertex<V> {
private DoublyLinkedList<Edge<E, V>> incidentEdges;
/* getter for incidentEdges */
}
class AdjacencyListEdge<V> extends EdgeListEdge<V> {
DLNode<Edge<E, V>> originIncidentListPos;
DLNode<Edge<E, V>> destIncidentListPos;
}
34 of 55
O(m)
O(m)
36 of 55
Graphs in Java: Adjacency List (2)
Graphs in Java: Adjacency List (4)
Iterable<Edge<E, V>> outgoingEdges(Vertex<V> v) {
ArrayList<Edge<E, V>> oes = new ArrayList<>();
DLNode<Edge<E, V>> current = v.getIncidentEdges() .first();
while(current != null) {
/* directed graph: add edge if v is the origin
* undirected graph: add edge if v is one of the end points
*/
if ( current.origin == v ||
class AdjacencyListGraph<V, E> implements Graph<V, E> {
private DoublyLinkedList< AdjacencyListVertex <V>> vertices;
private DoublyLinkedList< AdjacencyListEdge <E, V>> edges;
private boolean isDirected;
( current.dest == v && !isDirected
oes.add(current.getElement());
/* initialize an empty graph */
AdjacencyListGraph(boolean isDirected) {
vertices = new DoublyLinkedList<>();
edges = new DoublyLinkedList<>();
this.isDirected = isDirected;
}
)) {
}
current = current.getNext();
}
return oes;
}
Running Time?
O(dv )
Exercise: Iterable<Edge<E, V>> incomingEdges(Vertex<V> v)
Exercise: int outDegree(Vertex<V> v)
37 of 55
39 of 55
Graphs in Java: Adjacency List (3)
22
2. Adjacency List Structure (cont.)
Edge<E, V> getEdge(Vertex<V> u, Vertex<V> v); {
Edge<E, V> e = null;
DLNode<Edge<E, V>> cur = degree(u) > degree(v) ?
v.getIncidentEdges() .first() :
V
B
o
B
A
p
I(B)
Graphs in Java: Adjacency List (5)
A
I(A)
u.getIncidentEdges() .first();
while(cur != null) {
/* directed graph: origin is u and destination is v
* undirected graph: order does not matter
*/
if ( cur.origin == u && cur.dest == v ||
C
I(C)
C
o
( cur.dest == u && cur.dest == v && !isDirected
edge = cur;
p
)) {
}
cur = cur.getNext();
}
return edge;
E
}
What is the cost and what steps are involved in executing incidentEdges(A)?
38 of 55
What is the cost and what steps are involved in executing adjacentVertices(A)?
What is the cost and what steps are involved in executing areAdjacent(A,B)?
Running Time?
40 of 55
O(min(du , dv ))
Graphs in Java: Adjacency List (6)
Graphs in Java: Adjacency Matrix (1)
Vertex<V> insertVertex(V element) {
Vertex<V> v = new AdjacencyListVertex(element);
v.setVertexListPosition(vertices.addLast(v));
}
• Extends the edge list structure
Edge<E, V> insertEdge(Vertex<V> u, Vertex<V> v, E element) {
EdgeListEdge<E, V> e = new AdjacencyListEdge<>(element, u, v);
e.setOriginIncidentListPos( u.getIncidentEdges() .addLast(e));
e.setDestIncidentListPos( v.getIncidentEdges() .addLast(e));
e.setEdgeListPosition(edges.addLast(e));
}
Running Time?
O(1)
• Each vertex v also stores an integer index that is used to index
into a 2-dimensional adjacency matrix .
) locating an edge between two vertices takes O(1)
class AdjacencyMatrixVertex<V> extends EdgeListVertex<V> {
private int index;
/* getter and setter for index */
}
Exercise: void removeEdge(Edge<E, V> e)
41 of 55
43 of 55
Graphs in Java: Adjacency List (7)
Graphs in Java: Adjacency Matrix (2)
class AdjacencyMatrixGraph<V, E> implements Graph<V, E> {
private DoublyLinkedList< AdjacencyMatrixVertex <V>> vertices;
void removeVertex(Vertex<V> v) {
vertices.remove(v.getVertexListPosition());
DLNode<Edge<E, V>> cur = v.getIncidentEdges() .first();
while(cur != null) {
/* each edge that is incident on v should be removed */
if ( cur.origin == v || cur.dest == v ) {
edges.remove(cur);
}
cur = cur.getNext();
}
}
Running Time?
42 of 55
private DoublyLinkedList< EdgeListEdge <E, V>> edges;
private EdgeListEdge<E, V>[][] matrix ;
private boolean isDirected;
/* initialize an empty graph */
AdjacencyMatrixGraph(boolean isDirected) {
vertices = new DoublyLinkedList<>();
edges = new DoublyLinkedList<>();
this.isDirected = isDirected;
}
O(dv )
Space Requirements?
44 of 55
O(n2 )
25
3. Adjacency Matrix Structure (cont.)
Graphs in Java: Adjacency Matrix (3)
Graphs in Java: Adjacency Matrix (5)
V
0
B
1
o
0 B
A
1
0
p
0
C 2
2
A
1
∅
1
2
C
2
undirected
graph
⇓
symmetric
matrix
∅
∅
∅
∅
o
p
Iterable<Edge<E, V>> outgoingEdges(Vertex<V> v) {
ArrayList<Edge<E, V>> oes = new ArrayList<>();
int row = v.getIndex();
for(int col = 0; col < numVertices(); col ++) {
Edge<E, V> oe = matrix[row][col];
if(oe != null) {
oes.add(oe);
}
}
return oes;
}
E
• Each row index in matrix represents an origin vertex.
is the cost and what steps are involved in executing areAdjacent(A,B)?
•What
Each
column index in matrix represents a destination vertex.
What is the cost and what steps are involved in executing incidentEdges(A)?
e.g., edge (B, A): matrix[0][1]
the cost and what steps are involved in executing adjacentVertices(A)?
•What
Foris an
undirected graph, cells are symmetric.
e.g., matrix[0][1] == matrix[1][0]
For a graph that is reasonably complete, |V | = n < |E| = m.
Exercise: Iterable<Edge<E, V>> incomingEdges(Vertex<V> v)
47 of 55
Graphs in Java: Adjacency Matrix (4)
Graphs in Java: Adjacency Matrix (6)
Edge<E, V> getEdge(Vertex<V> u, Vertex<V> v); {
Edge<E, V> e = matrix[u.getIndex()][v.getIndex()];
return e;
}
O(1) !
Vertex<V> insertVertex(V element) {
/* create a new, larger matrix */
EdgeListEdge<E, V>[][] newMatrix =
new EdgeListEdge<>[numVertices() + 1][numVertices() + 1];
/* transfer contents from old to new matrices */
for(int row = 0; row < numVertices(); row ++) {
for(int col = 0; col < numVertices(); col ++) {
newMatrix[row][col] = matrix[row][col];
}
}
/* add new vertex to the vertices list and set its position */
Vertex<V> v = new AdjacencyMatrixVertex(element);
v.setVertexListPosition(vertices.addLast(v));
/* reassign adjacency matrix to the new, larger matrix */
matrix = newMatrix;
}
Running Time?
Exercise: void removeVertex(Vertex<V> v)
46 of 55
O(n)
Exercise: int outDegree(Vertex<V> v)
45 of 55
Running Time?
Running Time?
48 of 55
O(n2 )
Graphs in Java: Adjacency Matrix (7)
Graphs in Java: Comparison of Strategies (2)
E DGE L IST
Edge<E, V> insertEdge(Vertex<V> u, Vertex<V> v, E element) {
EdgeListEdge<E, V> e = new EdgeListEdge<>(element, u, v);
matrix[u.getIndex()][v.getIndex()] = e;
if(!isDirected) {
matrix[v.getIndex()][u.getIndex()] = e;
}
e.setEdgeListPosition(edges.addLast(e));
}
Running Time?
O(1)
Exercise: void removeEdge(Edge<E, V> e)
49 of 55
V ERTEX
E DGE L IST
A DJACENCY M ATRIX
50 of 55
A DJACENCY L IST
A DJACENCY M ATRIX
O(1)
O(m)
O(n)
O(m)
O(min(du , dv ))
O(1)
O(m)
O(1)
O(n)
O(m)
O(dv )
O(n)
O(dv )
O(n2 )
O(n2 )
O(1)
O(m)
O(1)
51 of 55
Graphs in Java: Comparison of Strategies (1)
A DJACENCY L IST
numVertices()
numEdges()
vertices()
edges()
getEdge(u, v)
outDegree()
inDegree()
outgoingEdges(v)
incomingEdges(v)
insertVertex(x)
removeVertex(v)
insertEdge(u, v, x)
removeEdge(e)
incidentEdges
vertexListPosition
index
E DGE
originIncidentListPos
destIncidentListPos
edgeListPosition
G RAPH
isDirected
vertices
edges
matrix
Index (1)
Graphs: Definition
Directed vs. Undirected Edges
Self vs. Parallel Edges
Vertices
Exercise (1)
Directed vs. Undirected Graphs
Directed Graph Example (1): A Flight Network
Directed Graph Example (2): Class Inheritance
Undirected Graph Example (1): London Tube
Undirected Graph Example (2): Co-authorship
Basic Properties of Graphs (1)
Basic Properties of Graphs (2)
Basic Properties of Graphs (3)
Paths and Cycles (1)
52 of 55
Index (2)
Index (4)
Paths and Cycles (2)
Subgraphs vs. Spanning Subgraphs
Connected Graph vs. Connected Components
Forests vs. Trees
Spanning Trees
Exercise (2)
Basic Properties of Graphs (4)
Graphs in Java: Doubly-Linked Node and List
Graphs in Java: Vertex and Edge
Graphs in Java: Interface (1)
Graphs in Java: Interface (2)
Graphs in Java: Interface (3)
Graphs in Java: Edge List (1)
Graphs in Java: Edge List (2)
Graphs in Java: Adjacency Matrix (2)
53 of 55
Index (3)
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
Graphs in Java:
54 of 55
Edge List (3)
Edge List (4)
Edge List (5)
Edge List (6)
Edge List (7)
Edge List (8)
Adjacency List (1)
Adjacency List (2)
Adjacency List (3)
Adjacency List (4)
Adjacency List (5)
Adjacency List (6)
Adjacency List (7)
Adjacency Matrix (1)
Graphs in Java: Adjacency Matrix (3)
Graphs in Java: Adjacency Matrix (4)
Graphs in Java: Adjacency Matrix (5)
Graphs in Java: Adjacency Matrix (6)
Graphs in Java: Adjacency Matrix (7)
Graphs in Java: Comparison of Strategies (1)
Graphs in Java: Comparison of Strategies (2)
55 of 55