SlideShare a Scribd company logo
Lecture 10:
    Graph Data Structures
         Steven Skiena

Department of Computer Science
 State University of New York
 Stony Brook, NY 11794–4400

http://www.cs.sunysb.edu/∼skiena
Sort Yourselves
Sort yourselves in alphabetical order so I can return the
midterms efficiently!
Graphs
Graphs are one of the unifying themes of computer science.
A graph G = (V, E) is defined by a set of vertices V , and
a set of edges E consisting of ordered or unordered pairs of
vertices from V .
Road Networks
In modeling a road network, the vertices may represent the
cities or junctions, certain pairs of which are connected by
roads/edges.
                                  Stony Brook                 Green Port

                                                                                      Orient Point
              vertices - cities
                                                Riverhead
              edges - roads
                                                                     Shelter Island




                                                                                      Montauk
                                  Islip                     Sag Harbor
Electronic Circuits
In an electronic circuit, with junctions as vertices as
components as edges.
                                 vertices: junctions

                                 edges: components
Flavors of Graphs
The first step in any graph problem is determining which
flavor of graph you are dealing with.
Learning to talk the talk is an important part of walking the
walk.
The flavor of graph has a big impact on which algorithms are
appropriate and efficient.
Directed vs. Undirected Graphs
A graph G = (V, E) is undirected if edge (x, y) ∈ E implies
that (y, x) is also in E.



                   undirected     directed




Road networks between cities are typically undirected.
Street networks within cities are almost always directed
because of one-way streets.
Most graphs of graph-theoretic interest are undirected.
Weighted vs. Unweighted Graphs
In weighted graphs, each edge (or vertex) of G is assigned a
numerical value, or weight.
                                                          5
                                     7
                                                                  2
                                                  3
                                         9            3

                                 5                    4       7

                                             12

                    unweighted           weighted




The edges of a road network graph might be weighted with
their length, drive-time or speed limit.
In unweighted graphs, there is no cost distinction between
various edges and vertices.
Simple vs. Non-simple Graphs
Certain types of edges complicate the task of working with
graphs. A self-loop is an edge (x, x) involving only one
vertex.
An edge (x, y) is a multi-edge if it occurs more than once in
the graph.



                     simple        nonāˆ’simple




Any graph which avoids these structures is called simple.
Sparse vs. Dense Graphs
Graphs are sparse when only a small fraction of the possible
number of vertex pairs actually have edges defined between
them.



                    sparse         dense




Graphs are usually sparse due to application-specific con-
straints. Road networks must be sparse because of road
junctions.
Typically dense graphs have a quadratic number of edges
while sparse graphs are linear in size.
Cyclic vs. Acyclic Graphs
An acyclic graph does not contain any cycles. Trees are
connected acyclic undirected graphs.




                   cyclic            acyclic




Directed acyclic graphs are called DAGs. They arise naturally
in scheduling problems, where a directed edge (x, y) indicates
that x must occur before y.
Implicit vs. Explicit Graphs
Many graphs are not explicitly constructed and then tra-
versed, but built as we use them.



                   explicit   implicit




A good example arises in backtrack search.
Embedded vs. Topological Graphs
A graph is embedded if the vertices and edges have been
assigned geometric positions.



                    embedded      topological




Example: TSP or Shortest path on points in the plane.
Example: Grid graphs.
Example: Planar graphs.
Labeled vs. Unlabeled Graphs
In labeled graphs, each vertex is assigned a unique name or
identifier to distinguish it from all other vertices.
                                       B                  D


                                A                     E
                                              C



                                G                 F

                    unlabeled       labeled




An important graph problem is isomorphism testing, deter-
mining whether the topological structure of two graphs are in
fact identical if we ignore any labels.
The Friendship Graph
Consider a graph where the vertices are people, and there is
an edge between two people if and only if they are friends.
                 Ronald Reagan                    Frank Sinatra




                 George Bush                      Nancy Reagan




                                 Saddam Hussain




This graph is well-defined on any set of people: SUNY SB,
New York, or the world.
What questions might we ask about the friendship graph?
If I am your friend, does that mean you are my
friend?
A graph is undirected if (x, y) implies (y, x). Otherwise the
graph is directed.
The ā€œheard-ofā€ graph is directed since countless famous
people have never heard of me!
The ā€œhad-sex-withā€ graph is presumably undirected, since it
requires a partner.
Am I my own friend?
An edge of the form (x, x) is said to be a loop.
If x is y’s friend several times over, that could be modeled
using multiedges, multiple edges between the same pair of
vertices.
A graph is said to be simple if it contains no loops and
multiple edges.
Am I linked by some chain of friends to the
President?
A path is a sequence of edges connecting two vertices. Since
Mel Brooks is my father’s-sister’s-husband’s cousin, there is
a path between me and him!

                 Steve   Dad   Aunt Eve   Uncle Lenny   Cousin Mel
How close is my link to the President?
If I were trying to impress you with how tight I am with Mel
Brooks, I would be much better off saying that Uncle Lenny
knows him than to go into the details of how connected I am
to Uncle Lenny.
Thus we are often interested in the shortest path between two
nodes.
Is there a path of friends between any two
people?
A graph is connected if there is a path between any two
vertices.
A directed graph is strongly connected if there is a directed
path between any two vertices.
Who has the most friends?
The degree of a vertex is the number of edges adjacent to it.
Data Structures for Graphs: Adjacency Matrix
There are two main data structures used to represent graphs.
We assume the graph G = (V, E) contains n vertices and m
edges.
We can represent G using an n Ɨ n matrix M , where element
M [i, j] is, say, 1, if (i, j) is an edge of G, and 0 if it isn’t. It
may use excessive space for graphs with many vertices and
relatively few edges, however.
Can we save space if (1) the graph is undirected? (2) if the
graph is sparse?
Adjacency Lists
An adjacency list consists of a N Ɨ 1 array of pointers, where
the ith element points to a linked list of the edges incident on
vertex i.
             1        2
                                    1   2   3

                                    2   1   5   3   4
                             3      3   2   4

                                    4   2   5   3

             5        4             5   4   1   2




To test if edge (i, j) is in the graph, we search the ith list for
j, which takes O(di ), where di is the degree of the ith vertex.
Note that di can be much less than n when the graph is sparse.
If necessary, the two copies of each edge can be linked by a
pointer to facilitate deletions.
Tradeoffs Between Adjacency Lists and
Adjacency Matrices

               Comparison                                         Winner
               Faster to test if (x, y) exists?                  matrices
               Faster to find vertex degree?                           lists
               Less memory on small graphs?       lists (m + n) vs. (n2)
               Less memory on big graphs?           matrices (small win)
               Edge insertion or deletion?                  matrices O(1)
               Faster to traverse the graph?           lists m + n vs. n2
               Better for most problems?                              lists



Both representations are very useful and have different
properties, although adjacency lists are probably better for
most problems.
Adjancency List Representation

#define MAXV 100

typedef struct {
      int y;
      int weight;
      struct edgenode *next;
} edgenode;
Edge Representation

typedef struct {
      edgenode *edges[MAXV+1];
      int degree[MAXV+1];
      int nvertices;
      int nedges;
      bool directed;
} graph;


The degree field counts the number of meaningful entries for
the given vertex. An undirected edge (x, y) appears twice in
any adjacency-based graph structure, once as y in x’s list, and
once as x in y’s list.
Initializing a Graph

initialize graph(graph *g, bool directed)
{
       int i;

      g āˆ’ > nvertices = 0;
      g āˆ’ > nedges = 0;
      g āˆ’ > directed = directed;

      for (i=1; i<=MAXV; i++) gāˆ’ >degree[i] = 0;
      for (i=1; i<=MAXV; i++) gāˆ’ >edges[i] = NULL;
}
Reading a Graph
A typical graph format consists of an initial line featuring
the number of vertices and edges in the graph, followed by
a listing of the edges at one vertex pair per line.
read graph(graph *g, bool directed)
{     int i;
      int m;
      int x, y;

      initialize graph(g, directed);

      scanf(ā€%d %dā€,&(gāˆ’ >nvertices),&m);

      for (i=1; i<=m; i++) {
             scanf(ā€%d %dā€,&x,&y);
             insert edge(g,x,y,directed);
      }
}
Inserting an Edge

insert edge(graph *g, int x, int y, bool directed)
{
       edgenode *p;

      p = malloc(sizeof(edgenode));

      pāˆ’ >weight = NULL;
      pāˆ’ >y = y;
      pāˆ’ >next = gāˆ’ >edges[x];

      gāˆ’ >edges[x] = p;

      gāˆ’ >degree[x] ++;

      if (directed == FALSE)
             insert edge(g,y,x,TRUE);
      else
             gāˆ’ >nedges ++;
}

More Related Content

What's hot (20)

PDF
Linear algebra-Basis & Dimension
Manikanta satyala
Ā 
PDF
Basic galois field arithmatics required for error control codes
Madhumita Tamhane
Ā 
PDF
introduction to graph theory
Chuckie Balbuena
Ā 
PPTX
Introduction to Graph Theory
Manash Kumar Mondal
Ā 
PPT
Spanning trees
Shareb Ismaeel
Ā 
PPTX
Newton’s Divided Difference Formula
Jas Singh Bhasin
Ā 
PPT
Graph colouring
Priyank Jain
Ā 
PPTX
Find Transitive Closure Using Floyd-Warshall Algorithm
Rajib Roy
Ā 
PPTX
Graph representation
Tech_MX
Ā 
PPTX
Connectivity of graph
Shameer P Hamsa
Ā 
PPTX
Graph Basic In Data structure
Ikhlas Rahman
Ā 
PDF
Graph theory in network system
Manikanta satyala
Ā 
PPT
Regulafalsi_bydinesh
Dinesh Kumar
Ā 
PDF
Visualising Multi Dimensional Data
Amit Kapoor
Ā 
PPT
Binary trees
Simratpreet Singh
Ā 
PPTX
Graph data structure and algorithms
Anandhasilambarasan D
Ā 
PDF
Fibonacci Heap
Anshuman Biswal
Ā 
PPTX
BISECTION METHOD
St Mary's College,Thrissur,Kerala
Ā 
PPTX
graph theory
ganith2k13
Ā 
PPTX
B and B+ tree
Ashish Arun
Ā 
Linear algebra-Basis & Dimension
Manikanta satyala
Ā 
Basic galois field arithmatics required for error control codes
Madhumita Tamhane
Ā 
introduction to graph theory
Chuckie Balbuena
Ā 
Introduction to Graph Theory
Manash Kumar Mondal
Ā 
Spanning trees
Shareb Ismaeel
Ā 
Newton’s Divided Difference Formula
Jas Singh Bhasin
Ā 
Graph colouring
Priyank Jain
Ā 
Find Transitive Closure Using Floyd-Warshall Algorithm
Rajib Roy
Ā 
Graph representation
Tech_MX
Ā 
Connectivity of graph
Shameer P Hamsa
Ā 
Graph Basic In Data structure
Ikhlas Rahman
Ā 
Graph theory in network system
Manikanta satyala
Ā 
Regulafalsi_bydinesh
Dinesh Kumar
Ā 
Visualising Multi Dimensional Data
Amit Kapoor
Ā 
Binary trees
Simratpreet Singh
Ā 
Graph data structure and algorithms
Anandhasilambarasan D
Ā 
Fibonacci Heap
Anshuman Biswal
Ā 
graph theory
ganith2k13
Ā 
B and B+ tree
Ashish Arun
Ā 

Viewers also liked (20)

PPT
Graph algorithm
University of Potsdam
Ā 
PDF
Algorithms of graph
getacew
Ā 
PPT
Ch18
leminhvuong
Ā 
PPTX
Graph in data structure
Abrish06
Ā 
PPT
Basic Mathematics (PPISMP) - representing data into bar graph
T-ah Atirah
Ā 
PDF
02 newton-raphson
stephanus_ananda
Ā 
PPTX
Parallel Algorithms for Geometric Graph Problems (at Stanford)
Grigory Yaroslavtsev
Ā 
PPTX
Spark MLlib - Training Material
Bryan Yang
Ā 
PDF
Skiena algorithm 2007 lecture12 topological sort connectivity
zukun
Ā 
PPT
Simple algorithm & hopcroft karp for bipartite graph
Miguel Pereira
Ā 
PPT
Minimum spanning tree
Hinal Lunagariya
Ā 
PPTX
Minimum spanning Tree
Narendra Singh Patel
Ā 
PPTX
Minimum Spanning Tree
zhaokatherine
Ā 
PPTX
My presentation minimum spanning tree
Alona Salva
Ā 
PPTX
Spanning trees & applications
Tech_MX
Ā 
PPT
Prim's Algorithm on minimum spanning tree
oneous
Ā 
PPTX
Matrix Representation Of Graph
Abhishek Pachisia
Ā 
PPTX
Graph data structure
Tech_MX
Ā 
PPT
2.2 topological sort 02
Krish_ver2
Ā 
Graph algorithm
University of Potsdam
Ā 
Algorithms of graph
getacew
Ā 
Ch18
leminhvuong
Ā 
Graph in data structure
Abrish06
Ā 
Basic Mathematics (PPISMP) - representing data into bar graph
T-ah Atirah
Ā 
02 newton-raphson
stephanus_ananda
Ā 
Parallel Algorithms for Geometric Graph Problems (at Stanford)
Grigory Yaroslavtsev
Ā 
Spark MLlib - Training Material
Bryan Yang
Ā 
Skiena algorithm 2007 lecture12 topological sort connectivity
zukun
Ā 
Simple algorithm & hopcroft karp for bipartite graph
Miguel Pereira
Ā 
Minimum spanning tree
Hinal Lunagariya
Ā 
Minimum spanning Tree
Narendra Singh Patel
Ā 
Minimum Spanning Tree
zhaokatherine
Ā 
My presentation minimum spanning tree
Alona Salva
Ā 
Spanning trees & applications
Tech_MX
Ā 
Prim's Algorithm on minimum spanning tree
oneous
Ā 
Matrix Representation Of Graph
Abhishek Pachisia
Ā 
Graph data structure
Tech_MX
Ā 
2.2 topological sort 02
Krish_ver2
Ā 
Ad

Similar to Skiena algorithm 2007 lecture10 graph data strctures (20)

PPT
Graphs in data structures
Savit Chandra
Ā 
PPTX
Lecture 4- Design Analysis Of ALgorithms
mtahanasir65
Ā 
PPT
Lecture 5b graphs and hashing
Victor Palmar
Ā 
PPTX
Graph in data structure
Pooja Bhojwani
Ā 
PPTX
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
Ā 
PPTX
DATA STRUCTURES unit 4.pptx
ShivamKrPathak
Ā 
PPT
Graph
Mudassar Mushtaq
Ā 
PPTX
graph.pptx
DEEPAK948083
Ā 
PPTX
Graphs.pptx
satvikkushwaha1
Ā 
PPTX
Data structure graphs
Uma mohan
Ā 
PPT
lec 09-graphs-bfs-dfs.ppt
TalhaFarooqui12
Ā 
PPTX
Graph Theory
Rashmi Bhat
Ā 
PPTX
Graphs aktu notes computer networks.pptx
TalhaKhan528682
Ā 
PPTX
Graph terminology and algorithm and tree.pptx
asimshahzad8611
Ā 
PPTX
ppt 1.pptx
ShasidharaniD
Ā 
PDF
unit-3-dsa-graph introduction to grapgh and graph type
sayalijscoe2
Ā 
DOC
Magtibay buk bind#2
Sofia Palawan
Ā 
PPSX
Design and analysis of Algorithms Lecture 1 (BFS, DFS).ppsx
SababAshfakFahim
Ā 
PDF
Graphs
Dwight Sabio
Ā 
Graphs in data structures
Savit Chandra
Ā 
Lecture 4- Design Analysis Of ALgorithms
mtahanasir65
Ā 
Lecture 5b graphs and hashing
Victor Palmar
Ā 
Graph in data structure
Pooja Bhojwani
Ā 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
Ā 
DATA STRUCTURES unit 4.pptx
ShivamKrPathak
Ā 
graph.pptx
DEEPAK948083
Ā 
Graphs.pptx
satvikkushwaha1
Ā 
Data structure graphs
Uma mohan
Ā 
lec 09-graphs-bfs-dfs.ppt
TalhaFarooqui12
Ā 
Graph Theory
Rashmi Bhat
Ā 
Graphs aktu notes computer networks.pptx
TalhaKhan528682
Ā 
Graph terminology and algorithm and tree.pptx
asimshahzad8611
Ā 
ppt 1.pptx
ShasidharaniD
Ā 
unit-3-dsa-graph introduction to grapgh and graph type
sayalijscoe2
Ā 
Magtibay buk bind#2
Sofia Palawan
Ā 
Design and analysis of Algorithms Lecture 1 (BFS, DFS).ppsx
SababAshfakFahim
Ā 
Graphs
Dwight Sabio
Ā 
Ad

More from zukun (20)

PDF
My lyn tutorial 2009
zukun
Ā 
PDF
ETHZ CV2012: Tutorial openCV
zukun
Ā 
PDF
ETHZ CV2012: Information
zukun
Ā 
PDF
Siwei lyu: natural image statistics
zukun
Ā 
PDF
Lecture9 camera calibration
zukun
Ā 
PDF
Brunelli 2008: template matching techniques in computer vision
zukun
Ā 
PDF
Modern features-part-4-evaluation
zukun
Ā 
PDF
Modern features-part-3-software
zukun
Ā 
PDF
Modern features-part-2-descriptors
zukun
Ā 
PDF
Modern features-part-1-detectors
zukun
Ā 
PDF
Modern features-part-0-intro
zukun
Ā 
PDF
Lecture 02 internet video search
zukun
Ā 
PDF
Lecture 01 internet video search
zukun
Ā 
PDF
Lecture 03 internet video search
zukun
Ā 
PDF
Icml2012 tutorial representation_learning
zukun
Ā 
PPT
Advances in discrete energy minimisation for computer vision
zukun
Ā 
PDF
Gephi tutorial: quick start
zukun
Ā 
PDF
EM algorithm and its application in probabilistic latent semantic analysis
zukun
Ā 
PDF
Object recognition with pictorial structures
zukun
Ā 
PDF
Iccv2011 learning spatiotemporal graphs of human activities
zukun
Ā 
My lyn tutorial 2009
zukun
Ā 
ETHZ CV2012: Tutorial openCV
zukun
Ā 
ETHZ CV2012: Information
zukun
Ā 
Siwei lyu: natural image statistics
zukun
Ā 
Lecture9 camera calibration
zukun
Ā 
Brunelli 2008: template matching techniques in computer vision
zukun
Ā 
Modern features-part-4-evaluation
zukun
Ā 
Modern features-part-3-software
zukun
Ā 
Modern features-part-2-descriptors
zukun
Ā 
Modern features-part-1-detectors
zukun
Ā 
Modern features-part-0-intro
zukun
Ā 
Lecture 02 internet video search
zukun
Ā 
Lecture 01 internet video search
zukun
Ā 
Lecture 03 internet video search
zukun
Ā 
Icml2012 tutorial representation_learning
zukun
Ā 
Advances in discrete energy minimisation for computer vision
zukun
Ā 
Gephi tutorial: quick start
zukun
Ā 
EM algorithm and its application in probabilistic latent semantic analysis
zukun
Ā 
Object recognition with pictorial structures
zukun
Ā 
Iccv2011 learning spatiotemporal graphs of human activities
zukun
Ā 

Recently uploaded (20)

PDF
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
Ā 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
Ā 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
Ā 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
Ā 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
Ā 
PDF
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
Ā 
PDF
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
Ā 
PPTX
Top Managed Service Providers in Los Angeles
Captain IT
Ā 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
Ā 
PPTX
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
Ā 
PPTX
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
Ā 
PDF
July Patch Tuesday
Ivanti
Ā 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
Ā 
PDF
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
Ā 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
Ā 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
Ā 
PDF
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
Ā 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
Ā 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
Ā 
PDF
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
Ā 
Human-centred design in online workplace learning and relationship to engagem...
Tracy Tang
Ā 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
Ā 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
Ā 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
Ā 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
Ā 
Impact of IEEE Computer Society in Advancing Emerging Technologies including ...
Hironori Washizaki
Ā 
Meetup Kickoff & Welcome - Rohit Yadav, CSIUG Chairman
ShapeBlue
Ā 
Top Managed Service Providers in Los Angeles
Captain IT
Ā 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
Ā 
Top iOS App Development Company in the USA for Innovative Apps
SynapseIndia
Ā 
Building and Operating a Private Cloud with CloudStack and LINBIT CloudStack ...
ShapeBlue
Ā 
July Patch Tuesday
Ivanti
Ā 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
Ā 
Windsurf Meetup Ottawa 2025-07-12 - Planning Mode at Reliza.pdf
Pavel Shukhman
Ā 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
Ā 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
Ā 
Rethinking Security Operations - SOC Evolution Journey.pdf
Haris Chughtai
Ā 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
Ā 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
Ā 
CloudStack GPU Integration - Rohit Yadav
ShapeBlue
Ā 

Skiena algorithm 2007 lecture10 graph data strctures

  • 1. Lecture 10: Graph Data Structures Steven Skiena Department of Computer Science State University of New York Stony Brook, NY 11794–4400 http://www.cs.sunysb.edu/∼skiena
  • 2. Sort Yourselves Sort yourselves in alphabetical order so I can return the midterms efficiently!
  • 3. Graphs Graphs are one of the unifying themes of computer science. A graph G = (V, E) is defined by a set of vertices V , and a set of edges E consisting of ordered or unordered pairs of vertices from V .
  • 4. Road Networks In modeling a road network, the vertices may represent the cities or junctions, certain pairs of which are connected by roads/edges. Stony Brook Green Port Orient Point vertices - cities Riverhead edges - roads Shelter Island Montauk Islip Sag Harbor
  • 5. Electronic Circuits In an electronic circuit, with junctions as vertices as components as edges. vertices: junctions edges: components
  • 6. Flavors of Graphs The first step in any graph problem is determining which flavor of graph you are dealing with. Learning to talk the talk is an important part of walking the walk. The flavor of graph has a big impact on which algorithms are appropriate and efficient.
  • 7. Directed vs. Undirected Graphs A graph G = (V, E) is undirected if edge (x, y) ∈ E implies that (y, x) is also in E. undirected directed Road networks between cities are typically undirected. Street networks within cities are almost always directed because of one-way streets. Most graphs of graph-theoretic interest are undirected.
  • 8. Weighted vs. Unweighted Graphs In weighted graphs, each edge (or vertex) of G is assigned a numerical value, or weight. 5 7 2 3 9 3 5 4 7 12 unweighted weighted The edges of a road network graph might be weighted with their length, drive-time or speed limit. In unweighted graphs, there is no cost distinction between various edges and vertices.
  • 9. Simple vs. Non-simple Graphs Certain types of edges complicate the task of working with graphs. A self-loop is an edge (x, x) involving only one vertex. An edge (x, y) is a multi-edge if it occurs more than once in the graph. simple nonāˆ’simple Any graph which avoids these structures is called simple.
  • 10. Sparse vs. Dense Graphs Graphs are sparse when only a small fraction of the possible number of vertex pairs actually have edges defined between them. sparse dense Graphs are usually sparse due to application-specific con- straints. Road networks must be sparse because of road junctions. Typically dense graphs have a quadratic number of edges while sparse graphs are linear in size.
  • 11. Cyclic vs. Acyclic Graphs An acyclic graph does not contain any cycles. Trees are connected acyclic undirected graphs. cyclic acyclic Directed acyclic graphs are called DAGs. They arise naturally in scheduling problems, where a directed edge (x, y) indicates that x must occur before y.
  • 12. Implicit vs. Explicit Graphs Many graphs are not explicitly constructed and then tra- versed, but built as we use them. explicit implicit A good example arises in backtrack search.
  • 13. Embedded vs. Topological Graphs A graph is embedded if the vertices and edges have been assigned geometric positions. embedded topological Example: TSP or Shortest path on points in the plane. Example: Grid graphs. Example: Planar graphs.
  • 14. Labeled vs. Unlabeled Graphs In labeled graphs, each vertex is assigned a unique name or identifier to distinguish it from all other vertices. B D A E C G F unlabeled labeled An important graph problem is isomorphism testing, deter- mining whether the topological structure of two graphs are in fact identical if we ignore any labels.
  • 15. The Friendship Graph Consider a graph where the vertices are people, and there is an edge between two people if and only if they are friends. Ronald Reagan Frank Sinatra George Bush Nancy Reagan Saddam Hussain This graph is well-defined on any set of people: SUNY SB, New York, or the world. What questions might we ask about the friendship graph?
  • 16. If I am your friend, does that mean you are my friend? A graph is undirected if (x, y) implies (y, x). Otherwise the graph is directed. The ā€œheard-ofā€ graph is directed since countless famous people have never heard of me! The ā€œhad-sex-withā€ graph is presumably undirected, since it requires a partner.
  • 17. Am I my own friend? An edge of the form (x, x) is said to be a loop. If x is y’s friend several times over, that could be modeled using multiedges, multiple edges between the same pair of vertices. A graph is said to be simple if it contains no loops and multiple edges.
  • 18. Am I linked by some chain of friends to the President? A path is a sequence of edges connecting two vertices. Since Mel Brooks is my father’s-sister’s-husband’s cousin, there is a path between me and him! Steve Dad Aunt Eve Uncle Lenny Cousin Mel
  • 19. How close is my link to the President? If I were trying to impress you with how tight I am with Mel Brooks, I would be much better off saying that Uncle Lenny knows him than to go into the details of how connected I am to Uncle Lenny. Thus we are often interested in the shortest path between two nodes.
  • 20. Is there a path of friends between any two people? A graph is connected if there is a path between any two vertices. A directed graph is strongly connected if there is a directed path between any two vertices.
  • 21. Who has the most friends? The degree of a vertex is the number of edges adjacent to it.
  • 22. Data Structures for Graphs: Adjacency Matrix There are two main data structures used to represent graphs. We assume the graph G = (V, E) contains n vertices and m edges. We can represent G using an n Ɨ n matrix M , where element M [i, j] is, say, 1, if (i, j) is an edge of G, and 0 if it isn’t. It may use excessive space for graphs with many vertices and relatively few edges, however. Can we save space if (1) the graph is undirected? (2) if the graph is sparse?
  • 23. Adjacency Lists An adjacency list consists of a N Ɨ 1 array of pointers, where the ith element points to a linked list of the edges incident on vertex i. 1 2 1 2 3 2 1 5 3 4 3 3 2 4 4 2 5 3 5 4 5 4 1 2 To test if edge (i, j) is in the graph, we search the ith list for j, which takes O(di ), where di is the degree of the ith vertex. Note that di can be much less than n when the graph is sparse. If necessary, the two copies of each edge can be linked by a pointer to facilitate deletions.
  • 24. Tradeoffs Between Adjacency Lists and Adjacency Matrices Comparison Winner Faster to test if (x, y) exists? matrices Faster to find vertex degree? lists Less memory on small graphs? lists (m + n) vs. (n2) Less memory on big graphs? matrices (small win) Edge insertion or deletion? matrices O(1) Faster to traverse the graph? lists m + n vs. n2 Better for most problems? lists Both representations are very useful and have different properties, although adjacency lists are probably better for most problems.
  • 25. Adjancency List Representation #define MAXV 100 typedef struct { int y; int weight; struct edgenode *next; } edgenode;
  • 26. Edge Representation typedef struct { edgenode *edges[MAXV+1]; int degree[MAXV+1]; int nvertices; int nedges; bool directed; } graph; The degree field counts the number of meaningful entries for the given vertex. An undirected edge (x, y) appears twice in any adjacency-based graph structure, once as y in x’s list, and once as x in y’s list.
  • 27. Initializing a Graph initialize graph(graph *g, bool directed) { int i; g āˆ’ > nvertices = 0; g āˆ’ > nedges = 0; g āˆ’ > directed = directed; for (i=1; i<=MAXV; i++) gāˆ’ >degree[i] = 0; for (i=1; i<=MAXV; i++) gāˆ’ >edges[i] = NULL; }
  • 28. Reading a Graph A typical graph format consists of an initial line featuring the number of vertices and edges in the graph, followed by a listing of the edges at one vertex pair per line. read graph(graph *g, bool directed) { int i; int m; int x, y; initialize graph(g, directed); scanf(ā€%d %dā€,&(gāˆ’ >nvertices),&m); for (i=1; i<=m; i++) { scanf(ā€%d %dā€,&x,&y); insert edge(g,x,y,directed); } }
  • 29. Inserting an Edge insert edge(graph *g, int x, int y, bool directed) { edgenode *p; p = malloc(sizeof(edgenode)); pāˆ’ >weight = NULL; pāˆ’ >y = y; pāˆ’ >next = gāˆ’ >edges[x]; gāˆ’ >edges[x] = p; gāˆ’ >degree[x] ++; if (directed == FALSE) insert edge(g,y,x,TRUE); else gāˆ’ >nedges ++; }