SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
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 ++;
}

Weitere ähnliche Inhalte

Was ist angesagt?

ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra Sahil Kumar
 
Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Randa Elanwar
 
MATLAB for Technical Computing
MATLAB for Technical ComputingMATLAB for Technical Computing
MATLAB for Technical ComputingNaveed Rehman
 
EG UNIT-IV SECTION OF SOLIDS.ppt
EG UNIT-IV SECTION OF SOLIDS.pptEG UNIT-IV SECTION OF SOLIDS.ppt
EG UNIT-IV SECTION OF SOLIDS.pptGanesamoorthy14
 
Lesson 9-development-of-surfaces-i
Lesson 9-development-of-surfaces-iLesson 9-development-of-surfaces-i
Lesson 9-development-of-surfaces-ieglive
 
Engineering drawing-part-4
Engineering drawing-part-4Engineering drawing-part-4
Engineering drawing-part-4musadoto
 
NAS-Ch4-Application of Laplace Transform
NAS-Ch4-Application of Laplace TransformNAS-Ch4-Application of Laplace Transform
NAS-Ch4-Application of Laplace TransformHussain K
 
Liang barsky Line Clipping Algorithm
Liang barsky Line Clipping AlgorithmLiang barsky Line Clipping Algorithm
Liang barsky Line Clipping AlgorithmArvind Kumar
 
Find Transitive closure of a Graph Using Warshall's Algorithm
Find Transitive closure of a Graph Using Warshall's AlgorithmFind Transitive closure of a Graph Using Warshall's Algorithm
Find Transitive closure of a Graph Using Warshall's AlgorithmSafayet Hossain
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabBilawalBaloch1
 
Bezier Curve in Computer Graphics.docx
Bezier Curve in Computer Graphics.docxBezier Curve in Computer Graphics.docx
Bezier Curve in Computer Graphics.docxbcanawakadalcollege
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - GraphMadhu Bala
 
Section 2 part 1 coordinate transformation
Section 2   part 1 coordinate transformationSection 2   part 1 coordinate transformation
Section 2 part 1 coordinate transformationEJDamman
 

Was ist angesagt? (20)

Eg unit ii projection of lines
Eg unit ii projection of linesEg unit ii projection of lines
Eg unit ii projection of lines
 
Engineering Curves
Engineering CurvesEngineering Curves
Engineering Curves
 
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
ADA - Minimum Spanning Tree Prim Kruskal and Dijkstra
 
Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4Introduction to matlab lecture 1 of 4
Introduction to matlab lecture 1 of 4
 
MATLAB for Technical Computing
MATLAB for Technical ComputingMATLAB for Technical Computing
MATLAB for Technical Computing
 
Sub matrices - Circuit Matrix
Sub matrices - Circuit MatrixSub matrices - Circuit Matrix
Sub matrices - Circuit Matrix
 
EG UNIT-IV SECTION OF SOLIDS.ppt
EG UNIT-IV SECTION OF SOLIDS.pptEG UNIT-IV SECTION OF SOLIDS.ppt
EG UNIT-IV SECTION OF SOLIDS.ppt
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
Orthographic projections
Orthographic projectionsOrthographic projections
Orthographic projections
 
Lesson 9-development-of-surfaces-i
Lesson 9-development-of-surfaces-iLesson 9-development-of-surfaces-i
Lesson 9-development-of-surfaces-i
 
Engineering drawing-part-4
Engineering drawing-part-4Engineering drawing-part-4
Engineering drawing-part-4
 
NAS-Ch4-Application of Laplace Transform
NAS-Ch4-Application of Laplace TransformNAS-Ch4-Application of Laplace Transform
NAS-Ch4-Application of Laplace Transform
 
Liang barsky Line Clipping Algorithm
Liang barsky Line Clipping AlgorithmLiang barsky Line Clipping Algorithm
Liang barsky Line Clipping Algorithm
 
Matlab ppt
Matlab pptMatlab ppt
Matlab ppt
 
L3 cfg
L3 cfgL3 cfg
L3 cfg
 
Find Transitive closure of a Graph Using Warshall's Algorithm
Find Transitive closure of a Graph Using Warshall's AlgorithmFind Transitive closure of a Graph Using Warshall's Algorithm
Find Transitive closure of a Graph Using Warshall's Algorithm
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Bezier Curve in Computer Graphics.docx
Bezier Curve in Computer Graphics.docxBezier Curve in Computer Graphics.docx
Bezier Curve in Computer Graphics.docx
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 
Section 2 part 1 coordinate transformation
Section 2   part 1 coordinate transformationSection 2   part 1 coordinate transformation
Section 2 part 1 coordinate transformation
 

Andere mochten auch

Algorithms of graph
Algorithms of graphAlgorithms of graph
Algorithms of graphgetacew
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structureAbrish06
 
Basic Mathematics (PPISMP) - representing data into bar graph
Basic Mathematics (PPISMP) - representing data into bar graphBasic Mathematics (PPISMP) - representing data into bar graph
Basic Mathematics (PPISMP) - representing data into bar graphT-ah Atirah
 
Parallel Algorithms for Geometric Graph Problems (at Stanford)
Parallel Algorithms for Geometric Graph Problems (at Stanford)Parallel Algorithms for Geometric Graph Problems (at Stanford)
Parallel Algorithms for Geometric Graph Problems (at Stanford)Grigory Yaroslavtsev
 
Spark MLlib - Training Material
Spark MLlib - Training Material Spark MLlib - Training Material
Spark MLlib - Training Material Bryan Yang
 
Skiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivitySkiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivityzukun
 
Simple algorithm & hopcroft karp for bipartite graph
Simple algorithm & hopcroft karp for bipartite graphSimple algorithm & hopcroft karp for bipartite graph
Simple algorithm & hopcroft karp for bipartite graphMiguel Pereira
 
Minimum Spanning Tree
Minimum Spanning TreeMinimum Spanning Tree
Minimum Spanning Treezhaokatherine
 
My presentation minimum spanning tree
My presentation minimum spanning treeMy presentation minimum spanning tree
My presentation minimum spanning treeAlona Salva
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applicationsTech_MX
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treeoneous
 
Matrix Representation Of Graph
Matrix Representation Of GraphMatrix Representation Of Graph
Matrix Representation Of GraphAbhishek Pachisia
 
Graph data structure
Graph data structureGraph data structure
Graph data structureTech_MX
 
2.2 topological sort 02
2.2 topological sort 022.2 topological sort 02
2.2 topological sort 02Krish_ver2
 

Andere mochten auch (20)

Graph algorithm
Graph algorithmGraph algorithm
Graph algorithm
 
Algorithms of graph
Algorithms of graphAlgorithms of graph
Algorithms of graph
 
Ch18
Ch18Ch18
Ch18
 
Graph in data structure
Graph in data structureGraph in data structure
Graph in data structure
 
Basic Mathematics (PPISMP) - representing data into bar graph
Basic Mathematics (PPISMP) - representing data into bar graphBasic Mathematics (PPISMP) - representing data into bar graph
Basic Mathematics (PPISMP) - representing data into bar graph
 
02 newton-raphson
02 newton-raphson02 newton-raphson
02 newton-raphson
 
Parallel Algorithms for Geometric Graph Problems (at Stanford)
Parallel Algorithms for Geometric Graph Problems (at Stanford)Parallel Algorithms for Geometric Graph Problems (at Stanford)
Parallel Algorithms for Geometric Graph Problems (at Stanford)
 
Spark MLlib - Training Material
Spark MLlib - Training Material Spark MLlib - Training Material
Spark MLlib - Training Material
 
Skiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivitySkiena algorithm 2007 lecture12 topological sort connectivity
Skiena algorithm 2007 lecture12 topological sort connectivity
 
Simple algorithm & hopcroft karp for bipartite graph
Simple algorithm & hopcroft karp for bipartite graphSimple algorithm & hopcroft karp for bipartite graph
Simple algorithm & hopcroft karp for bipartite graph
 
Minimum spanning tree
Minimum spanning treeMinimum spanning tree
Minimum spanning tree
 
Minimum spanning Tree
Minimum spanning TreeMinimum spanning Tree
Minimum spanning Tree
 
Minimum Spanning Tree
Minimum Spanning TreeMinimum Spanning Tree
Minimum Spanning Tree
 
My presentation minimum spanning tree
My presentation minimum spanning treeMy presentation minimum spanning tree
My presentation minimum spanning tree
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Prim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning treePrim's Algorithm on minimum spanning tree
Prim's Algorithm on minimum spanning tree
 
Matrix Representation Of Graph
Matrix Representation Of GraphMatrix Representation Of Graph
Matrix Representation Of Graph
 
Graph data structure
Graph data structureGraph data structure
Graph data structure
 
Lecture8 data structure(graph)
Lecture8 data structure(graph)Lecture8 data structure(graph)
Lecture8 data structure(graph)
 
2.2 topological sort 02
2.2 topological sort 022.2 topological sort 02
2.2 topological sort 02
 

Ähnlich wie Skiena algorithm 2007 lecture10 graph data strctures

Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashingVictor Palmar
 
FREQUENT SUBGRAPH MINING ALGORITHMS - A SURVEY AND FRAMEWORK FOR CLASSIFICATION
FREQUENT SUBGRAPH MINING ALGORITHMS - A SURVEY AND FRAMEWORK FOR CLASSIFICATIONFREQUENT SUBGRAPH MINING ALGORITHMS - A SURVEY AND FRAMEWORK FOR CLASSIFICATION
FREQUENT SUBGRAPH MINING ALGORITHMS - A SURVEY AND FRAMEWORK FOR CLASSIFICATIONcscpconf
 
Graph theory concepts complex networks presents-rouhollah nabati
Graph theory concepts   complex networks presents-rouhollah nabatiGraph theory concepts   complex networks presents-rouhollah nabati
Graph theory concepts complex networks presents-rouhollah nabatinabati
 
Graph Databases: Trends in the Web of Data
Graph Databases: Trends in the Web of DataGraph Databases: Trends in the Web of Data
Graph Databases: Trends in the Web of DataMarko Rodriguez
 
Graph Introduction.ppt
Graph Introduction.pptGraph Introduction.ppt
Graph Introduction.pptFaruk Hossen
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data StructureKeno benti
 
ON ALGORITHMIC PROBLEMS CONCERNING GRAPHS OF HIGHER DEGREE OF SYMMETRY
ON ALGORITHMIC PROBLEMS CONCERNING GRAPHS OF HIGHER DEGREE OF SYMMETRYON ALGORITHMIC PROBLEMS CONCERNING GRAPHS OF HIGHER DEGREE OF SYMMETRY
ON ALGORITHMIC PROBLEMS CONCERNING GRAPHS OF HIGHER DEGREE OF SYMMETRYFransiskeran
 
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...Marko Rodriguez
 
Graph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptxGraph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptxasimshahzad8611
 
Slides Chapter10.1 10.2
Slides Chapter10.1 10.2Slides Chapter10.1 10.2
Slides Chapter10.1 10.2showslidedump
 
On algorithmic problems concerning graphs of higher degree of symmetry
On algorithmic problems concerning graphs of higher degree of symmetryOn algorithmic problems concerning graphs of higher degree of symmetry
On algorithmic problems concerning graphs of higher degree of symmetrygraphhoc
 
Discrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part IDiscrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part IWongyos Keardsri
 
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjteUnit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjtepournima055
 
Graceful labelings
Graceful labelingsGraceful labelings
Graceful labelingsradhikamathy
 
Lecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxLecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxking779879
 

Ähnlich wie Skiena algorithm 2007 lecture10 graph data strctures (20)

Lecture 5b graphs and hashing
Lecture 5b graphs and hashingLecture 5b graphs and hashing
Lecture 5b graphs and hashing
 
FREQUENT SUBGRAPH MINING ALGORITHMS - A SURVEY AND FRAMEWORK FOR CLASSIFICATION
FREQUENT SUBGRAPH MINING ALGORITHMS - A SURVEY AND FRAMEWORK FOR CLASSIFICATIONFREQUENT SUBGRAPH MINING ALGORITHMS - A SURVEY AND FRAMEWORK FOR CLASSIFICATION
FREQUENT SUBGRAPH MINING ALGORITHMS - A SURVEY AND FRAMEWORK FOR CLASSIFICATION
 
Graph theory concepts complex networks presents-rouhollah nabati
Graph theory concepts   complex networks presents-rouhollah nabatiGraph theory concepts   complex networks presents-rouhollah nabati
Graph theory concepts complex networks presents-rouhollah nabati
 
Spanningtreesppt
SpanningtreespptSpanningtreesppt
Spanningtreesppt
 
Graph Databases: Trends in the Web of Data
Graph Databases: Trends in the Web of DataGraph Databases: Trends in the Web of Data
Graph Databases: Trends in the Web of Data
 
Graph Introduction.ppt
Graph Introduction.pptGraph Introduction.ppt
Graph Introduction.ppt
 
Graph Data Structure
Graph Data StructureGraph Data Structure
Graph Data Structure
 
Graphs data structures
Graphs data structuresGraphs data structures
Graphs data structures
 
ON ALGORITHMIC PROBLEMS CONCERNING GRAPHS OF HIGHER DEGREE OF SYMMETRY
ON ALGORITHMIC PROBLEMS CONCERNING GRAPHS OF HIGHER DEGREE OF SYMMETRYON ALGORITHMIC PROBLEMS CONCERNING GRAPHS OF HIGHER DEGREE OF SYMMETRY
ON ALGORITHMIC PROBLEMS CONCERNING GRAPHS OF HIGHER DEGREE OF SYMMETRY
 
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
Problem-Solving using Graph Traversals: Searching, Scoring, Ranking, and Reco...
 
Graph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptxGraph terminology and algorithm and tree.pptx
Graph terminology and algorithm and tree.pptx
 
26 spanning
26 spanning26 spanning
26 spanning
 
Graph
GraphGraph
Graph
 
Slides Chapter10.1 10.2
Slides Chapter10.1 10.2Slides Chapter10.1 10.2
Slides Chapter10.1 10.2
 
On algorithmic problems concerning graphs of higher degree of symmetry
On algorithmic problems concerning graphs of higher degree of symmetryOn algorithmic problems concerning graphs of higher degree of symmetry
On algorithmic problems concerning graphs of higher degree of symmetry
 
Discrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part IDiscrete-Chapter 11 Graphs Part I
Discrete-Chapter 11 Graphs Part I
 
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjteUnit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
Unit II_Graph.pptxkgjrekjgiojtoiejhgnltegjte
 
Graphs
GraphsGraphs
Graphs
 
Graceful labelings
Graceful labelingsGraceful labelings
Graceful labelings
 
Lecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptxLecture 2.3.1 Graph.pptx
Lecture 2.3.1 Graph.pptx
 

Mehr von zukun

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009zukun
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVzukun
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Informationzukun
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statisticszukun
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibrationzukun
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionzukun
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluationzukun
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-softwarezukun
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptorszukun
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectorszukun
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-introzukun
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video searchzukun
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video searchzukun
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video searchzukun
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learningzukun
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionzukun
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick startzukun
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysiszukun
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structureszukun
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities zukun
 

Mehr von zukun (20)

My lyn tutorial 2009
My lyn tutorial 2009My lyn tutorial 2009
My lyn tutorial 2009
 
ETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCVETHZ CV2012: Tutorial openCV
ETHZ CV2012: Tutorial openCV
 
ETHZ CV2012: Information
ETHZ CV2012: InformationETHZ CV2012: Information
ETHZ CV2012: Information
 
Siwei lyu: natural image statistics
Siwei lyu: natural image statisticsSiwei lyu: natural image statistics
Siwei lyu: natural image statistics
 
Lecture9 camera calibration
Lecture9 camera calibrationLecture9 camera calibration
Lecture9 camera calibration
 
Brunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer visionBrunelli 2008: template matching techniques in computer vision
Brunelli 2008: template matching techniques in computer vision
 
Modern features-part-4-evaluation
Modern features-part-4-evaluationModern features-part-4-evaluation
Modern features-part-4-evaluation
 
Modern features-part-3-software
Modern features-part-3-softwareModern features-part-3-software
Modern features-part-3-software
 
Modern features-part-2-descriptors
Modern features-part-2-descriptorsModern features-part-2-descriptors
Modern features-part-2-descriptors
 
Modern features-part-1-detectors
Modern features-part-1-detectorsModern features-part-1-detectors
Modern features-part-1-detectors
 
Modern features-part-0-intro
Modern features-part-0-introModern features-part-0-intro
Modern features-part-0-intro
 
Lecture 02 internet video search
Lecture 02 internet video searchLecture 02 internet video search
Lecture 02 internet video search
 
Lecture 01 internet video search
Lecture 01 internet video searchLecture 01 internet video search
Lecture 01 internet video search
 
Lecture 03 internet video search
Lecture 03 internet video searchLecture 03 internet video search
Lecture 03 internet video search
 
Icml2012 tutorial representation_learning
Icml2012 tutorial representation_learningIcml2012 tutorial representation_learning
Icml2012 tutorial representation_learning
 
Advances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer visionAdvances in discrete energy minimisation for computer vision
Advances in discrete energy minimisation for computer vision
 
Gephi tutorial: quick start
Gephi tutorial: quick startGephi tutorial: quick start
Gephi tutorial: quick start
 
EM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysisEM algorithm and its application in probabilistic latent semantic analysis
EM algorithm and its application in probabilistic latent semantic analysis
 
Object recognition with pictorial structures
Object recognition with pictorial structuresObject recognition with pictorial structures
Object recognition with pictorial structures
 
Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities Iccv2011 learning spatiotemporal graphs of human activities
Iccv2011 learning spatiotemporal graphs of human activities
 

Kürzlich hochgeladen

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 

Kürzlich hochgeladen (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 

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 ++; }