lecture 10 - university of california, san...
TRANSCRIPT
-
Page 1 of 24
CSE 100, UCSD: LEC 10
Lecture 10
✔ Graphs
✔ Vertices, edges, paths, cycles
✔ Sparse and dense graphs
✔ Representations: adjacency matrices and adjacency lists
✔ Implementation notes
Reading: Weiss, Chapter 9
-
Page 2 of 24
Midterm exam
s 1 and 2; corresponding
pages
CSE 100, UCSD: LEC 10
✔ Date and time: Thu May 7, during lecture time
✔ Place: lecture room
✔ Closed book, closed notes, no calculators
✔ Just bring something to write with, and picture ID
✔ Coverage: Lectures up to the exam; Programming assignmentreadings
✔ Practice exam: available online
✔ Information about using PeerWise available on the class web
✔ Midterm reviews:
✗ Discussion section May 6
-
Page 3 of 24
Kinds of data structures
etween pairs of nodes
o requirement for a s have a unique parent or
CSE 100, UCSD: LEC 10
✔ You are familiar with these kinds of data structures:
✗ unstructured structures: sets
✗ linear, sequential structures: arrays, linked lists
✗ hierarchical structures: trees
✔ Now we will look at graphs
✔ Graphs consist of
✗ a collection of elements, called “nodes” or “vertices”
✗ a set of connections, called “edges” or “links” or “arcs”, b
✔ Graphs are in general not hierarchical or sequential: there is ndistinguished root node or first node, no requirement that nodea unique successor, etc.
-
Page 4 of 24
Why graphs?
f a tree)...
case of a graph)...
any applications
een them, form a graph
ween them, form a graph
n them, form a graph
rm a graph
tations between them,
blem or playing a game, a graph
epresenting graphs, and
CSE 100, UCSD: LEC 10
✔ Trees are a generalization of lists (a list is just a special case o
✔ Graphs are a generalization of of trees (a tree is just a special
✔ So, graphs are very general structures and are very useful in m
✗ the set of machines on the internet, and network lines betw
✗ the set of statements in a program, and flow of control bet
✗ the set of web pages in the world, and HREF links betwee
✗ the set of transistors on a chip, and wires between them, fo
✗ the set of possible base sequences in a DNA gene, and muform a graph
✗ the set of possible situations that can arise in solving a proand moves that get you from one situation to another, form
✗ et cetera...
✔ We will look at a formal definition of a graph, some ways of rsome important algorithms on graphs
-
Page 5 of 24
Graphs: some definitions
dges E
nd w are connected by an
going from vertex v to may not also be an edge
, and an edge in E is a
he number of vertices |V|
CSE 100, UCSD: LEC 10
✔ A graph G = (V,E) consists of a set of vertices V and a set of e
✔ Each edge in E is a pair (v,w) such that v and w are in V.
✗ If G is an undirected graph, (v,w) in E means vertices v aedge in G. This (v,w) is an unordered pair
✗ If G is a directed graph, (v,w) in E means there is an edgevertex w in G. This (v,w) is an ordered pair; there may or (w,v) in E
✔ In a weighted graph, each edge also has a “weight” or “cost” ctriple (v,w,c)
✔ When talking about the size of a problem involving a graph, tand the number of edges |E| will be relevant
-
Page 6 of 24
Graphs: an example
}
V4
CSE 100, UCSD: LEC 10
✔ Here is an unweighted directed graph:
✔ V = { }
✔ |V| =
✔ E = {
✔ |E| =
V0 V1
V6V5
V2 V3
-
Page 7 of 24
Graphs: more definitions
vN in V such that (vi,
be zero)
edges in the path
except the first and last
e first and last vertices are e distinct)
graph (DAG)
xample:
CSE 100, UCSD: LEC 10
✔ A path in a graph G=(V,E) is a sequence of vertices v1, v2, ...,vi+1) is in E for all i = 1,...,N-1.
✔ The length of a path is the number of edges in the path (might
✔ The weighted length of a path is the sum of the weights of the
✔ A simple path is a path in which all the vertices are different (can be the same)
✔ A cycle in a directed graph is a path of length >= 1 in which ththe same (in an undirected graph, the edges in a cycle must b
✔ A simple cycle is a cycle that is a simple path
✔ If a directed graph has no cycles, it is called a directed acyclic
✗ Is the example graph on the previous page a DAG?
✗ Note: Every tree is a DAG, but not every DAG is a tree. E
V1
V4
V3V2
-
Page 8 of 24
Dense and sparse graphs
ve?
g itself): |V| edges
ding itself): |V| edges
s are distinct
|V| = |V|2
CSE 100, UCSD: LEC 10
✔ If a directed graph has |V| vertices, how many edges can it ha
✗ The first vertex can have an edge to every vertex (includin
✗ The second vertex can have an edge to every vertex (inclu
✗ ... and so on for each of the |V| vertices; and all these edge
✔ So, the maximum total number of edges possible is |E| = |V|x
✔ A graph with “close to” |V|2 edges is considered dense
✔ A graph with “closer to” |V| edges is considered sparse
-
Page 9 of 24
Representing graphs
CSE 100, UCSD: LEC 10
✔ There are two major techniques for representing graphs:
✗ Adjacency matrix
✗ Adjacency list
✔ Each of these has advantages and we will look at each
-
Page 10 of 24
Adjacency matrices
between vertices i and j
is an edge, “0” or “false”
r “infinity” if there is no
you could just use an
d so the matrix has
CSE 100, UCSD: LEC 10
✔ An adjacency matrix is a 2D array
✔ The [i][j] entry in the matrix encodes connectivity information
✗ For an unweighted graph, the entry is “1” or “true” if thereif there is no edge
✗ For a weighted graph, the entry is the weight of the edge, oedge
✗ For an undirected graph, the matrix will be symmetric (or upper-triangular matrix)
✔ There are |V| rows and |V| columns in an adjacency matrix, an |V|2 entries
✔ This is space inefficient for sparse graphs
-
Page 11 of 24
Adjacency matrix, an example
CSE 100, UCSD: LEC 10
✔ Fill in this adjacency matrix for the example graph:
0
1
2
3
4
5
6
0 1 2 3 4 5 6
-
Page 12 of 24
Adjacency lists
tices adjacent to it
list contains (a reference
weight of the edge
then vk’s adjacency list
graph is represented by rtices
h is much better than |V|2
CSE 100, UCSD: LEC 10
✔ An adjacency list representation uses, well, lists
✔ Each vertex in the graph has associated with it a list of the ver
✔ That is, if (vj, vk) is an edge in the graph, then vj’s adjacency to) vk
✗ For a weighted graph, the list entry would also contain the
✗ For an undirected graph, if vj’s adjacency list contains vk ,should contain vj
✔ Using an adjacency list representation, each edge in a directedone item in one list; and there are as many lists as there are ve
✔ Therefore the storage required is proportional to |V| + |E|, whicfor sparse graphs, and comparable to |V|2 for dense graphs
-
Page 13 of 24
Adjacency lists, an example
:
CSE 100, UCSD: LEC 10
✔ Write down the adjacency lists to represent the example graph
V0:
V1:
V2:
V3:
V4:
V5:
V6:
-
Page 14 of 24
Vertices, vertex names, and vertex indices
s associated with them by
named with the city name
ore convenient to be able
rix, or an index into an
akes sense to the user, ertex index numbers
e these (in addition to the
names with vertex index
rtices themselves, and...
sociated with that vertex
CSE 100, UCSD: LEC 10
✔ In a graph application, the vertices of a graph may have namethe user
✗ as one example, vertices may correspond to cities, and be
✔ Internally, within the implementation of the graph, it may be mto refer to a vertex using an integer number
✗ this number can be used as an index into an adjacency matarray of adjacency lists, etc.
✔ To translate between the internal representation and one that myou need some way to translate among names, vertices, and v
✔ So, in implementing a graph ADT, it is often convenient to havadjacency matrix or adjacency lists):
✗ A dictionary data structure, e.g. a hash table, that associatesnumbers, and...
✗ An array or vector, that associates vertex numbers with ve
✗ An instance variable in each vertex that stores the name as
-
Page 15 of 24
Vertices, vertex names, and vertex indices: A design
niquely identified by its responding Vertex object
er. One way is with these
the Graph; Vertex objects
ndex
ertex
ame
CSE 100, UCSD: LEC 10
✔ Internally within a Graph object, we will want a vertex to be uname, or its integer index number, or by the identity of its cor
✔ So, we will want a way to go from any one of those to any othmappings:
✔ Note: only vertex names move through the public interface to and indices are strictly part of the implementation
Name Ivia a Hashtable
Index Vvia a Vector
Vertex Nvia Vertex instance variable
-
Page 16 of 24
Graph, Vertex, and Edge
important classes we will
it a user to create an names of the vertices n adjacency list
pecifying “1” for edge rallel” directed edges for
ent useful graph ee
internally by the Graph nd its adjacency list (as a
are useful in
it is used internally by the ency list. As such, an
connecting to, and the
CSE 100, UCSD: LEC 10
✔ Following a natural object-oriented design approach, the mostdefine are Graph, Vertex, and Edge
✔ A Graph will represent a weighted directed graph. It will permempty graph, and to add edges to the graph by specifying the connected by the edge, and the edge cost. Internally, it uses arepresentation.
✗ In this framework, unweighted graphs can be handled by sweight; undirected graphs can be handled by having 2 “paeach undirected edge
✗ A Graph object may also provide operations which implemalgorithms such as shortest path and minimum spanning tr
✔ A Vertex will represent a vertex in a directed graph; it is usedclass. A Vertex contains a String representation of its name, aLinkedList). It may also contain other instance variables thatimplementing various graph operations.
✔ An Edge will represent an edge in a weighted directed graph; Graph class. Edge objects are the elements in a Vertex’s adjacEdge only needs to contain an integer index of the vertex it iscost of the edge.
-
Page 17 of 24
An implementation of a Graph class
ted directed graph
an unweighted directed
aph
cost 1
cost 1
cost 1
ms can be run on the
CSE 100, UCSD: LEC 10
✔ We will look at parts of an implementation of a Graph class
✔ This implementation uses adjacency lists to represent a weigh
✔ The example Graph would be set up like this (the example is graph, so costs are set equal to 1):
Graph g = new Graph(); // create an empty Gr
g.addEdge("V0","V1",1); //edge from V0 to V1,
g.addEdge("V1","V4",1); //edge from V1 to V4,
g.addEdge("V1","V3",1); //edge from V1 to V3,
// etc.
✔ After the Graph is set up with all its edges, interesting algorithgraph (more about these later)
-
Page 18 of 24
An Edge class
e Graph
s implicit
rtex of this edge
dge
CSE 100, UCSD: LEC 10
✔ Instances of this class are elements of the adjacency lists in th
/**
* This class defines the information in each
* item in an adjacency list.
*/
class Edge {
// Source vertex of edge i
public int dest; // Index of destination ve
public int cost; // Cost (weight) of this e
public Edge( int d, int c ) {
dest = d;
cost = c;
}
}
-
Page 19 of 24
A Vertex class
ex
r this Vertex
thms
thms
thms
of this Vertex
an empty adj list
CSE 100, UCSD: LEC 10
/**
* This class defines the basic information
* stored for each vertex.
*/
class Vertex {
String name; // The name of this Vert
List adj; // The adjacency list fo
int dist; // variable for use by algori
int prev; // variable for use by algori
int scratch; // variable for use by algori
Vertex( String nm ) {
name = nm; // name
adj = new LinkedList( ); // Start
}
}
-
Page 20 of 24
A Graph class
weighted graphs.
1;
>();
CSE 100, UCSD: LEC 10
/**
* A class instances of which represent directed
*/
public class Graph {
// Maps vertex name to number
private HashMap vertexMap;
// Vector of Vertexes in Graph
private Vector vertexVec;
private static final int NULL_VERTEX = -
public Graph() {
vertexVec = new Vector();
vertexMap = new HashMap
-
Page 21 of 24
Adding an edge, given the names of its vertices and its cost
aph.
int cost ) {
f necessary
before; add it
necessary
efore; add it
CSE 100, UCSD: LEC 10
/**
* Add the edge ( source, dest, cost ) to the gr
*/
public void addEdge( String source, String dest,
// get internal index of source, creating it i
Integer sourceNum = vertexMap.get(source);
if (sourceNum == null) // new vertex, not seen
sourceNum = addVertex(source);
// get internal index of dest, creating it if
Integer destNum = vertexMap.get(dest);
if (destNum == null) // new vertex, not seen b
destNum = addVertex(dest);
// now actually add the edge to the graph
internalAddEdge( sourceNum, destNum, cost );
}
-
Page 22 of 24
Adding a vertex, given its name
, and
and vertex Vector.
internal number
xVec,
vertexMap
CSE 100, UCSD: LEC 10
/**
* Add a vertex with the given name to the Graph
* return its internal number as an Integer.
* This involves adding entries to the Hashtable
* PRE: vertexName is not already in the Graph
*/
private int addVertex( String vertexName ) {
// get the next unused index; this will be the
int indx = vertexVec.size();
// create a new Vertex, put it at end of verte
// where it will have index indx
vertexVec.add( new Vertex(vertexName) );
// associate the vertex name and index in the
vertexMap.put( vertexName, indx );
// return the internal vertex number
return indx;
}
-
Page 23 of 24
Adding an edge, cont’d
ts vertices.
in vertexVec
t, int cost)
est Vertex
t, cost) );
CSE 100, UCSD: LEC 10
/**
* Add an edge given internal index numbers of i
* PRE: source and dest are indexes of Vertexes
*/
private void internalAddEdge(int source, int des
{
// get the source Vertex, and add an edge to d
// to its adjacency list
vertexVec.get( source ).adj.add( new Edge (des
}
-
Page 24 of 24
Next time
CSE 100, UCSD: LEC 10
✔ Algorithms on graphs
✔ Breadth first, depth first searches
✔ Shortest path in unweighted graphs
✔ Greedy algorithms
✔ Djikstra’s algorithm for shortest path in weighted graphs
Reading: Weiss, Chapter 9, 10
Lecture 10GraphsVertices, edges, paths, cyclesSparse and dense graphsRepresentations: adjacency matrices and adjacency listsImplementation notes Reading: Weiss, Chapter 9
Midterm examDate and time: Thu May 7, during lecture timePlace: lecture roomClosed book, closed notes, no calculatorsJust bring something to write with, and picture IDCoverage: Lectures up to the exam; Programming assignments 1 and 2; corresponding readingsPractice exam: available onlineInformation about using PeerWise available on the class web pagesMidterm reviews:Discussion section May 6
Kinds of data structuresYou are familiar with these kinds of data structures:unstructured structures: setslinear, sequential structures: arrays, linked listshierarchical structures: trees
Now we will look at graphsGraphs consist ofa collection of elements, called “nodes” or “vertices”a set of connections, called “edges” or “links” or “arcs”, between pairs of nodes
Graphs are in general not hierarchical or sequential: there is no requirement for a distinguished...
Why graphs?Trees are a generalization of lists (a list is just a special case of a tree)...Graphs are a generalization of of trees (a tree is just a special case of a graph)...So, graphs are very general structures and are very useful in many applicationsthe set of machines on the internet, and network lines between them, form a graphthe set of statements in a program, and flow of control between them, form a graphthe set of web pages in the world, and HREF links between them, form a graphthe set of transistors on a chip, and wires between them, form a graphthe set of possible base sequences in a DNA gene, and mutations between them, form a graphthe set of possible situations that can arise in solving a problem or playing a game, and moves t...et cetera...
We will look at a formal definition of a graph, some ways of representing graphs, and some import...
Graphs: some definitionsA graph G = (V,E) consists of a set of vertices V and a set of edges EEach edge in E is a pair (v,w) such that v and w are in V.If G is an undirected graph, �(v,w) in E means vertices v and w are connected by an edge in G. Th...If G is a directed graph, (v,w) in E means there is an edge going from vertex v to vertex w in G....
In a weighted graph, each edge also has a “weight” or “cost” c, and an edge in E is a triple (v,w,c)When talking about the size of a problem involving a graph, the number of vertices |V| and the nu...
Graphs: an exampleHere is an unweighted directed graph:V = { }|V| =E = { }|E| =
Graphs: more definitionsA path in a graph G=(V,E) is a sequence of vertices v1, v2, ..., vN in V such that (vi, vi+1) is ...The length of a path is the number of edges in the path (might be zero)The weighted length of a path is the sum of the weights of the edges in the pathA simple path is a path in which all the vertices are different (except the first and last can be...A cycle in a directed graph is a path of length >= 1 in which the first and last vertices are the...A simple cycle is a cycle that is a simple pathIf a directed graph has no cycles, it is called a directed acyclic graph (DAG)Is the example graph on the previous page a DAG?Note: Every tree is a DAG, but not every DAG is a tree. Example:
Dense and sparse graphsIf a directed graph has |V| vertices, how many edges can it have?The first vertex can have an edge to every vertex (including itself): |V| edgesThe second vertex can have an edge to every vertex (including itself): |V| edges... and so on for each of the |V| vertices; and all these edges are distinct
So, the maximum total number of edges possible is |E| = |V|x|V| = |V|2A graph with “close to” |V|2 edges is considered denseA graph with “closer to” |V| edges is considered sparse
Representing graphsThere are two major techniques for representing graphs:Adjacency matrixAdjacency list
Each of these has advantages and we will look at each
Adjacency matricesAn adjacency matrix is a 2D arrayThe [i][j] entry in the matrix encodes connectivity information between vertices i and jFor an unweighted graph, the entry is “1” or “true” if there is an edge, “0” or “false” if there ...For a weighted graph, the entry is the weight of the edge, or “infinity” if there is no edgeFor an undirected graph, the matrix will be symmetric (or you could just use an upper-triangular ...
There are |V| rows and |V| columns in an adjacency matrix, and so the matrix has |V|2 entriesThis is space inefficient for sparse graphs
Adjacency matrix, an exampleFill in this adjacency matrix for the example graph:
Adjacency listsAn adjacency list representation uses, well, listsEach vertex in the graph has associated with it a list of the vertices adjacent to itThat is, if (vj, vk) is an edge in the graph, then vj’s adjacency list contains (a reference to) vkFor a weighted graph, the list entry would also contain the weight of the edgeFor an undirected graph, if vj’s adjacency list contains vk , then vk’s adjacency list should con...
Using an adjacency list representation, each edge in a directed graph is represented by one item ...Therefore the storage required is proportional to |V| + |E|, which is much better than |V|2 for s...
Adjacency lists, an exampleWrite down the adjacency lists to represent the example graph: V0: V1: V2: V3: V4: V5: V6:
Vertices, vertex names, and vertex indicesIn a graph application, the vertices of a graph may have names associated with them by the useras one example, vertices may correspond to cities, and be named with the city name
Internally, within the implementation of the graph, it may be more convenient to be able to refer...this number can be used as an index into an adjacency matrix, or an index into an array of adjace...
To translate between the internal representation and one that makes sense to the user, you need s...So, in implementing a graph ADT, it is often convenient to have these (in addition to the adjacen...A dictionary data structure, e.g. a hash table, that associates names with vertex index numbers, ...An array or vector, that associates vertex numbers with vertices themselves, and...An instance variable in each vertex that stores the name associated with that vertex
Vertices, vertex names, and vertex indices: A designInternally within a Graph object, we will want a vertex to be uniquely identified by its name, or...So, we will want a way to go from any one of those to any other. One way is with these mappings:Note: only vertex names move through the public interface to the Graph; Vertex objects and indice...
Graph, Vertex, and EdgeFollowing a natural object-oriented design approach, the most important classes we will define ar...A Graph will represent a weighted directed graph. It will permit a user to create an empty graph,...In this framework, unweighted graphs can be handled by specifying “1” for edge weight; undirected...A Graph object may also provide operations which implement useful graph algorithms such as shorte...
A Vertex will represent a vertex in a directed graph; it is used internally by the Graph class. A...An Edge will represent an edge in a weighted directed graph; it is used internally by the Graph c...
An implementation of a Graph classWe will look at parts of an implementation of a Graph classThis implementation uses adjacency lists to represent a weighted directed graphThe example Graph would be set up like this (the example is an unweighted directed graph, so cost...Graph g = new Graph(); // create an empty Graphg.addEdge("V0","V1",1); //edge from V0 to V1, cost 1g.addEdge("V1","V4",1); //edge from V1 to V4, cost 1g.addEdge("V1","V3",1); //edge from V1 to V3, cost 1// etc.After the Graph is set up with all its edges, interesting algorithms can be run on the graph (mor...
An Edge classInstances of this class are elements of the adjacency lists in the Graph/*** This class defines the information in each* item in an adjacency list.*/class Edge {// Source vertex of edge is implicitpublic int dest; // Index of destination vertex of this edgepublic int cost; // Cost (weight) of this edgepublic Edge( int d, int c ) {dest = d;cost = c;}}
A Vertex class/*** This class defines the basic information* stored for each vertex.*/class Vertex {String name; // The name of this VertexList adj; // The adjacency list for this Vertexint dist; // variable for use by algorithmsint prev; // variable for use by algorithmsint scratch; // variable for use by algorithmsVertex( String nm ) {name = nm; // name of this Vertexadj = new LinkedList( ); // Start an empty adj list}}
A Graph class/*** A class instances of which represent directed weighted graphs.*/public class Graph {// Maps vertex name to numberprivate HashMap vertexMap;// Vector of Vertexes in Graphprivate Vector vertexVec;private static final int NULL_VERTEX = -1;public Graph() {vertexVec = new Vector();vertexMap = new HashMap();}
Adding an edge, given the names of its vertices and its cost/*** Add the edge ( source, dest, cost ) to the graph.*/public void addEdge( String source, String dest, int cost ) {// get internal index of source, creating it if necessaryInteger sourceNum = vertexMap.get(source);if (sourceNum == null) // new vertex, not seen before; add itsourceNum = addVertex(source);// get internal index of dest, creating it if necessaryInteger destNum = vertexMap.get(dest);if (destNum == null) // new vertex, not seen before; add itdestNum = addVertex(dest);// now actually add the edge to the graphinternalAddEdge( sourceNum, destNum, cost );}
Adding a vertex, given its name/*** Add a vertex with the given name to the Graph, and* return its internal number as an Integer.* This involves adding entries to the Hashtable and vertex Vector.* PRE: vertexName is not already in the Graph*/private int addVertex( String vertexName ) {// get the next unused index; this will be the internal numberint indx = vertexVec.size();// create a new Vertex, put it at end of vertexVec,// where it will have index indxvertexVec.add( new Vertex(vertexName) );// associate the vertex name and index in the vertexMapvertexMap.put( vertexName, indx );// return the internal vertex numberreturn indx;}
Adding an edge, cont’d/*** Add an edge given internal index numbers of its vertices.* PRE: source and dest are indexes of Vertexes in vertexVec*/private void internalAddEdge(int source, int dest, int cost){// get the source Vertex, and add an edge to dest Vertex// to its adjacency listvertexVec.get( source ).adj.add( new Edge (dest, cost) );}
Next timeAlgorithms on graphsBreadth first, depth first searchesShortest path in unweighted graphsGreedy algorithmsDjikstra’s algorithm for shortest path in weighted graphs Reading: Weiss, Chapter 9, 10