Graphs In Data Structure

Anuj Modi
Anuj ModiTrainee en VVDN Technologies
GRAPH
What is a Graph?
• A graph G = (V,E) is composed of:
    V: set of vertices
    E: set of edges connecting the vertices in V
• An edge e = (u,v) is a pair of vertices
• Example:
                a                           b      V= {a,b,c,d,e}

                                                   E= {(a,b),(a,c),
                              c                    (a,d),
                                                   (b,e),(c,d),(c,e),
                                                   (d,e)}
                d                           e
Applications
                                                       CS16
• electronic circuits




• networks (roads, flights, communications)


                                                 JFK

                     LAX                 STL
            HNL
                                   DFW
                                               FTL
Terminology:
Adjacent and Incident

• If (v0, v1) is an edge in an undirected graph,
   – v0 and v1 are adjacent
   – The edge (v0, v1) is incident on vertices v0 and v1
• If <v0, v1> is an edge in a directed graph
   – v0 is adjacent to v1, and v1 is adjacent from v0
   – The edge <v0, v1> is incident on v0 and v1
Terminology:
Degree of a Vertex
 The degree of a vertex is the number of edges
 incident to that vertex
 For directed graph,
   the in-degree of a vertex v is the number of edges
   that have v as the head
   the out-degree of a vertex v is the number of edges
   that have v as the tail
   if di is the degree of a vertex i in a graph G with n
   vertices and e edges, the number of edges is

          n −1

          ∑d ) / 2
                          Why? Since adjacent vertices each
   e =(          i        count the adjoining edge, it will be
           0
                          counted twice
Examples
                                             0
          3                                  2
          0                          1               2
                                     3               3
 3 1              2 3            3       4       5       6
          31
          G                      1      1 G2 1           1
              3
                        0    in:1, out: 1
 directed graph
 in-degree
 out-degree             1    in: 1, out: 2


                        2    in: 1, out: 0
                        G3
Terminology:
    Path

• path: sequence of
                                     3                             2
  vertices v1,v2,. . .vk such
  that consecutive vertices vi
                                                      3
  and vi+1 are adjacent.

                                      3                            3


                                 a                b       a            b


                                          c                    c

                                 d                e d                  e
                                     abedc                    bedc
                                              7
More Terminology
• simple path: no repeated vertices
                                     a                   b

                                                             bec
                                               c


                                     d                   e
• cycle: simple path, except that the last vertex is the same as the first
  vertex
               a                    b

                                               acda
                          c


               d                    e
Even More Terminology
•connected graph: any two vertices are connected by some path




                  connected               not connected
• subgraph: subset of vertices and edges forming a graph
• connected component: maximal connected subgraph. E.g., the graph below has
  3 connected components.
Subgraphs Examples
    0
             0             0                1            2             0
1        2
                       1            2            3             1               2
    3
    G1       (i)            (ii)             (iii)                     3(iv)
                           (a) Some of the subgraph of G1
    0
                   0            0                    0                  0

    1                           1                    1                  1


    2                                                2                  2
              (i)              (ii)                (iii)                   (iv)
                                      (b) Some of the subgraph of G3
    G3
More…
• tree - connected graph without cycles
• forest - collection of trees

                                         tree



                                                tree


                                forest

                 tree

                                         tree
Connectivity
• Let n = #vertices, and m = #edges
• A complete graph: one in which all pairs of vertices are
  adjacent
• How many total edges in a complete graph?
   – Each of the n vertices is incident to n-1 edges, however, we would
     have counted each edge twice! Therefore, intuitively, m = n(n -1)/2.
• Therefore, if a graph is not complete, m < n(n -1)/2



                                 n=5
                                 m = (5 ∗ 4)/2 = 10
More Connectivity

n = #vertices                  n=5
m = #edges                     m=4
• For a tree m = n - 1
If m < n - 1, G is
not connected

                         n=5
                         m=3
Oriented (Directed) Graph

• A graph where edges are directed
Directed vs. Undirected Graph

• An undirected graph is one in which the pair
  of vertices in a edge is unordered, (v0, v1) =
  (v1,v0)
• A directed graph is one in which each edge is
  a directed pair of vertices, <v0, v1> != <v1,v0>
                      tail          head
ADT for Graph
objects: a nonempty set of vertices and a set of undirected edges, where each
  edge is a pair of vertices
functions: for all graph ∈ Graph, v, v1 and v2 ∈ Vertices
 Graph Create()::=return an empty graph
 Graph InsertVertex(graph, v)::= return a graph with v inserted. v has no
                                incident edge.
 Graph InsertEdge(graph, v1,v2)::= return a graph with new edge
                                  between v1 and v2
 Graph DeleteVertex(graph, v)::= return a graph in which v and all edges
                                 incident to it are removed
 Graph DeleteEdge(graph, v1, v2)::=return a graph in which the edge (v1, v2)
                                   is removed
 Boolean IsEmpty(graph)::= if (graph==empty graph) return TRUE
                           else return FALSE
 List Adjacent(graph,v)::= return a list of all vertices that are adjacent to v
Graph Representations

 Adjacency Matrix
 Adjacency Lists
Adjacency Matrix

Let G=(V,E) be a graph with n vertices.
The adjacency matrix of G is a two-dimensional
n by n array, say adj_mat
If the edge (vi, vj) is in E(G), adj_mat[i][j]=1
If there is no such edge in E(G), adj_mat[i][j]=0
The adjacency matrix for an undirected graph is
symmetric; the adjacency matrix for a digraph
need not be symmetric
Examples for Adjacency Matrix
      0                                       0                    4
                       0
                                      2               1        5
1           2
                                              3                    6
      3                1
0    1 1 1               0 1 0
1    0 1 1                                                 7
                         1 0 1
                       2             0   1 1         0 0 0 0 0
1    1 0 1               0 0 0
                                   1
                                       0       0   1 0 0 0 0
                                                               
1    1 1 0
                                     1   0       0   1 0 0 0 0
                             G2                               
       G1
                                     0   1       1   0 0 0 0 0
                                     0   0       0   0 0 1 0 0
                                                              
                                     0   0       0   0 1 0 1 0
                   symmetric         0   0       0   0 0 1 0 1
                                                              
    undirected: n2/2                 0
                                         0       0   0 0 0 1 0
                                                               
    directed: n2
                                                          G4
Merits of Adjacency Matrix


From the adjacency matrix, to determine the
connection of vertices is easy
                           n −1

The degree of a vertex is ∑ adj _ mat[i][ j ]
                            j=0
For a digraph (= directed graph), the row sum is
the out_degree, while the column sum is the
in_degree
           n −1                       n −1
ind (vi ) = ∑ A[ j , i ] outd (vi ) = ∑ A[i , j ]
            j =0                      j =0
Adjacency Lists (data structures)

 Each row in adjacency matrix is represented as an adjacency list.

#define MAX_VERTICES 50
typedef struct node *node_pointer;
typedef struct node {
    int vertex;
    struct node *link;
};
node_pointer graph[MAX_VERTICES];
int n=0; /* vertices currently in use */
0                               0                    4
                                                   2       1        5
              1                 2                      3                    6
                       3                                            7
    0             1         2       3          0           1            2
    1             0         2       3          1           0            3
    2             0         1       3          2           0            3
    3             0         1       2          3           1            2
                           G1           0      4           5
                                               5           4            6
    0             1                            6           5            7
    1             0         2           1
                                               7           6
    2
                      G3                                   G4
                                        2
An undirected graph with n vertices and e edges ==> n head nodes and 2e list nodes
Some Operations
degree of a vertex in an undirected graph
 –# of nodes in adjacency list
# of edges in a graph
 –determined in O(n+e)
out-degree of a vertex in a directed graph
 –# of nodes in its adjacency list
in-degree of a vertex in a directed graph
 –traverse the whole data structure
Graph Traversal

• Problem: Search for a certain node or traverse
  all nodes in the graph
• Depth First Search
   – Once a possible path is found, continue the search
     until the end of the path
• Breadth First Search
   – Start several paths at a time, and advance in each
     one step at a time
Depth-First Search
        A     B      C   D


        E     F      G   H



        I     J      K   L


       M      N      O   P
Exploring a Labyrinth
      Without Getting Lost
• A depth-first search (DFS) in an undirected graph G is like wandering
  in a labyrinth with a string and a can of red paint without getting lost.
• We start at vertex s, tying the end of our string to the point and painting
  s “visited”. Next we label s as our current vertex called u.
• Now we travel along an arbitrary edge (u, v).
• If edge (u, v) leads us to an already visited vertex v we return to u.
• If vertex v is unvisited, we unroll our string and move to v, paint v
  “visited”, set v as our current vertex, and repeat the previous steps.
Breadth-First Search

• Like DFS, a Breadth-First Search (BFS) traverses a connected component of a
  graph, and in doing so defines a spanning tree with several useful properties.
• The starting vertex s has level 0, and, as in DFS, defines that point as an
  “anchor.”
• In the first round, the string is unrolled the length of one edge, and all of the
  edges that are only one edge away from the anchor are visited.
• These edges are placed into level 1
• In the second round, all the new edges that can be reached by unrolling the
  string 2 edges are visited and placed in level 2.
• This continues until every vertex has been assigned a level.
• The label of any vertex v corresponds to the length of the shortest path from s
  to v.


                                                            27
BFS - A Graphical Representation

          0                          0       1

          A          B       C   D   A       B        C     D


a)        E          F       G   H   E       F       G      H   b)

          I          J       K   L   I       J       K      L


          M          N       O   P   M       N        O     P
              0          1   2
                                         0       1     2    3
              A      B       C   D               B     C    D
                                         A
     c)                                                              d)
              E      F       G   H       E       F     G    H



                                         I       J     K    L
              I          J   K   L


              M      N       O   P
                                         M       N   28 O   P
More BFS

0   1   2      3       0   1   2   3

A   B   C      D       A   B   C   D


E   F   G      H       E   F   G   H

                   4                   4
I   J   K      L       I   J   K   L


M   N   O      P       M   N   O   P   5
Applications: Finding a Path

• Find path from source vertex s to destination
  vertex d
• Use graph search starting at s and terminating as
  soon as we reach d
   – Need to remember edges traversed
• Use depth – first search ?
• Use breath – first search?
DFS vs. BFS
                                F            B           A     start
DFS Process         E

                                G            D           C
                        destination


                                      C   DFS on C   D       Call DFS on D
              B DFS on B              B              B       Return to call on B
A DFS on A    A                       A              A


G   Call DFS on G   found destination - done!
D                   Path is implicitly stored in DFS recursion
B                   Path is: A, B, D, G
A
DFS vs. BFS
                                   F           B          A       start
                        E
BFS Process
                                  G            D          C
                        destination

rear         front          rear       front   rear       front            rear       front

              A                        B                D C                           D
 Initial call to BFS on A      Dequeue A           Dequeue B                 Dequeue C
 Add A to queue                   Add B             Add C, D              Nothing to add
  rear         front


               G              found destination - done!
       Dequeue D              Path must be stored separately
          Add G
1 de 32

Recomendados

Data structure - Graph por
Data structure - GraphData structure - Graph
Data structure - GraphMadhu Bala
6.4K vistas28 diapositivas
Graph in data structure por
Graph in data structureGraph in data structure
Graph in data structureAbrish06
43.2K vistas24 diapositivas
Graphs in data structure por
Graphs in data structureGraphs in data structure
Graphs in data structurehamza javed
1.8K vistas32 diapositivas
Graph representation por
Graph representationGraph representation
Graph representationTech_MX
37.3K vistas34 diapositivas
Graph theory presentation por
Graph theory presentationGraph theory presentation
Graph theory presentationAliul Kadir Akib
24.9K vistas24 diapositivas
Introduction to Graph Theory por
Introduction to Graph TheoryIntroduction to Graph Theory
Introduction to Graph TheoryPremsankar Chakkingal
35.2K vistas35 diapositivas

Más contenido relacionado

La actualidad más candente

Bfs and Dfs por
Bfs and DfsBfs and Dfs
Bfs and DfsMasud Parvaze
16.7K vistas33 diapositivas
Graph traversals in Data Structures por
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data StructuresAnandhasilambarasan D
4.5K vistas11 diapositivas
Graphs - Discrete Math por
Graphs - Discrete MathGraphs - Discrete Math
Graphs - Discrete MathSikder Tahsin Al-Amin
13.9K vistas18 diapositivas
Binary Tree Traversal por
Binary Tree TraversalBinary Tree Traversal
Binary Tree TraversalDhrumil Panchal
8.5K vistas18 diapositivas
Graph data structure and algorithms por
Graph data structure and algorithmsGraph data structure and algorithms
Graph data structure and algorithmsAnandhasilambarasan D
2.2K vistas10 diapositivas
Data structure computer graphs por
Data structure computer graphsData structure computer graphs
Data structure computer graphsKumar
4.4K vistas22 diapositivas

La actualidad más candente(20)

Data structure computer graphs por Kumar
Data structure computer graphsData structure computer graphs
Data structure computer graphs
Kumar 4.4K vistas
graph theory por ganith2k13
graph theory graph theory
graph theory
ganith2k1314.5K vistas
Graph traversal-BFS & DFS por Rajandeep Gill
Graph traversal-BFS & DFSGraph traversal-BFS & DFS
Graph traversal-BFS & DFS
Rajandeep Gill1.3K vistas
Graphs in Data Structure por hafsa komal
 Graphs in Data Structure Graphs in Data Structure
Graphs in Data Structure
hafsa komal2.2K vistas
trees in data structure por shameen khan
trees in data structure trees in data structure
trees in data structure
shameen khan3.5K vistas
Slides Chapter10.1 10.2 por showslidedump
Slides Chapter10.1 10.2Slides Chapter10.1 10.2
Slides Chapter10.1 10.2
showslidedump3.2K vistas
Application Of Graph Data Structure por Gaurang Dobariya
Application Of Graph Data StructureApplication Of Graph Data Structure
Application Of Graph Data Structure
Gaurang Dobariya14.9K vistas
Decoders por Re Man
DecodersDecoders
Decoders
Re Man7.7K vistas

Similar a Graphs In Data Structure

Graph por
GraphGraph
Graphsakthisree
3.3K vistas18 diapositivas
Graphs in data structures por
Graphs in data structuresGraphs in data structures
Graphs in data structuresSavit Chandra
1K vistas32 diapositivas
Unit 2: All por
Unit 2: AllUnit 2: All
Unit 2: AllHector Zenil
1.1K vistas110 diapositivas
Graph data structure por
Graph data structureGraph data structure
Graph data structureTech_MX
14.1K vistas28 diapositivas
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf por
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdfClass01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdfChristianKapsales1
4 vistas45 diapositivas
Graph por
GraphGraph
GraphMudassar Mushtaq
416 vistas52 diapositivas

Similar a Graphs In Data Structure(20)

Graph data structure por Tech_MX
Graph data structureGraph data structure
Graph data structure
Tech_MX14.1K vistas
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf por ChristianKapsales1
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdfClass01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Class01_Computer_Contest_Level_3_Notes_Sep_07 - Copy.pdf
Graphs por Mohd Arif
GraphsGraphs
Graphs
Mohd Arif5.6K vistas
Lecture 1--Graph Algorithms -- Basics.pptx por ChandanGiri21
Lecture 1--Graph Algorithms -- Basics.pptxLecture 1--Graph Algorithms -- Basics.pptx
Lecture 1--Graph Algorithms -- Basics.pptx
ChandanGiri2136 vistas
graph.pptx por hijigaf
graph.pptxgraph.pptx
graph.pptx
hijigaf16 vistas
Graph representation por DEEPIKA T
Graph representationGraph representation
Graph representation
DEEPIKA T45 vistas
Ppt of graph theory por ArvindBorge
Ppt of graph theoryPpt of graph theory
Ppt of graph theory
ArvindBorge625 vistas
Graphs (Models & Terminology) por zunaira saleem
Graphs (Models & Terminology)Graphs (Models & Terminology)
Graphs (Models & Terminology)
zunaira saleem150 vistas
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring por Saurabh Kaushik
Graph Theory,Graph Terminologies,Planar Graph & Graph ColouringGraph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Graph Theory,Graph Terminologies,Planar Graph & Graph Colouring
Saurabh Kaushik10.7K vistas

Más de Anuj Modi

Android Technology por
Android TechnologyAndroid Technology
Android TechnologyAnuj Modi
3K vistas24 diapositivas
Virtual memory por
Virtual memoryVirtual memory
Virtual memoryAnuj Modi
37.2K vistas15 diapositivas
Timing and-control-unit por
Timing and-control-unitTiming and-control-unit
Timing and-control-unitAnuj Modi
59.2K vistas22 diapositivas
Synchronous and-asynchronous-data-transfer por
Synchronous and-asynchronous-data-transferSynchronous and-asynchronous-data-transfer
Synchronous and-asynchronous-data-transferAnuj Modi
61.5K vistas18 diapositivas
Registers and-common-bus por
Registers and-common-busRegisters and-common-bus
Registers and-common-busAnuj Modi
26.3K vistas15 diapositivas
Ram and-rom-chips por
Ram and-rom-chipsRam and-rom-chips
Ram and-rom-chipsAnuj Modi
22.8K vistas10 diapositivas

Más de Anuj Modi(20)

Android Technology por Anuj Modi
Android TechnologyAndroid Technology
Android Technology
Anuj Modi3K vistas
Virtual memory por Anuj Modi
Virtual memoryVirtual memory
Virtual memory
Anuj Modi37.2K vistas
Timing and-control-unit por Anuj Modi
Timing and-control-unitTiming and-control-unit
Timing and-control-unit
Anuj Modi59.2K vistas
Synchronous and-asynchronous-data-transfer por Anuj Modi
Synchronous and-asynchronous-data-transferSynchronous and-asynchronous-data-transfer
Synchronous and-asynchronous-data-transfer
Anuj Modi61.5K vistas
Registers and-common-bus por Anuj Modi
Registers and-common-busRegisters and-common-bus
Registers and-common-bus
Anuj Modi26.3K vistas
Ram and-rom-chips por Anuj Modi
Ram and-rom-chipsRam and-rom-chips
Ram and-rom-chips
Anuj Modi22.8K vistas
Memory por Anuj Modi
MemoryMemory
Memory
Anuj Modi1.9K vistas
Computer instructions por Anuj Modi
Computer instructionsComputer instructions
Computer instructions
Anuj Modi31.7K vistas
Cache memory por Anuj Modi
Cache memoryCache memory
Cache memory
Anuj Modi55.5K vistas
HTML Lesson 5-insert-and-align-graphics por Anuj Modi
HTML Lesson 5-insert-and-align-graphicsHTML Lesson 5-insert-and-align-graphics
HTML Lesson 5-insert-and-align-graphics
Anuj Modi423 vistas
HTML Lesson 2-format-pages-and-text por Anuj Modi
HTML Lesson 2-format-pages-and-textHTML Lesson 2-format-pages-and-text
HTML Lesson 2-format-pages-and-text
Anuj Modi591 vistas
HTML Lesson 1-create-a-home-page por Anuj Modi
HTML Lesson 1-create-a-home-pageHTML Lesson 1-create-a-home-page
HTML Lesson 1-create-a-home-page
Anuj Modi1.1K vistas
Introduction to-dbms por Anuj Modi
Introduction to-dbmsIntroduction to-dbms
Introduction to-dbms
Anuj Modi1.1K vistas
Data models por Anuj Modi
Data modelsData models
Data models
Anuj Modi18.8K vistas
Architecture of-dbms-and-data-independence por Anuj Modi
Architecture of-dbms-and-data-independenceArchitecture of-dbms-and-data-independence
Architecture of-dbms-and-data-independence
Anuj Modi22.8K vistas
Central Processing Unit User View por Anuj Modi
Central Processing Unit User ViewCentral Processing Unit User View
Central Processing Unit User View
Anuj Modi5.1K vistas
Microprogram Control por Anuj Modi
Microprogram Control Microprogram Control
Microprogram Control
Anuj Modi54.2K vistas
Graphs In Data Structure por Anuj Modi
Graphs In Data StructureGraphs In Data Structure
Graphs In Data Structure
Anuj Modi1.1K vistas
B trees in Data Structure por Anuj Modi
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
Anuj Modi53.6K vistas

Graphs In Data Structure

  • 2. What is a Graph? • A graph G = (V,E) is composed of: V: set of vertices E: set of edges connecting the vertices in V • An edge e = (u,v) is a pair of vertices • Example: a b V= {a,b,c,d,e} E= {(a,b),(a,c), c (a,d), (b,e),(c,d),(c,e), (d,e)} d e
  • 3. Applications CS16 • electronic circuits • networks (roads, flights, communications) JFK LAX STL HNL DFW FTL
  • 4. Terminology: Adjacent and Incident • If (v0, v1) is an edge in an undirected graph, – v0 and v1 are adjacent – The edge (v0, v1) is incident on vertices v0 and v1 • If <v0, v1> is an edge in a directed graph – v0 is adjacent to v1, and v1 is adjacent from v0 – The edge <v0, v1> is incident on v0 and v1
  • 5. Terminology: Degree of a Vertex The degree of a vertex is the number of edges incident to that vertex For directed graph, the in-degree of a vertex v is the number of edges that have v as the head the out-degree of a vertex v is the number of edges that have v as the tail if di is the degree of a vertex i in a graph G with n vertices and e edges, the number of edges is n −1 ∑d ) / 2 Why? Since adjacent vertices each e =( i count the adjoining edge, it will be 0 counted twice
  • 6. Examples 0 3 2 0 1 2 3 3 3 1 2 3 3 4 5 6 31 G 1 1 G2 1 1 3 0 in:1, out: 1 directed graph in-degree out-degree 1 in: 1, out: 2 2 in: 1, out: 0 G3
  • 7. Terminology: Path • path: sequence of 3 2 vertices v1,v2,. . .vk such that consecutive vertices vi 3 and vi+1 are adjacent. 3 3 a b a b c c d e d e abedc bedc 7
  • 8. More Terminology • simple path: no repeated vertices a b bec c d e • cycle: simple path, except that the last vertex is the same as the first vertex a b acda c d e
  • 9. Even More Terminology •connected graph: any two vertices are connected by some path connected not connected • subgraph: subset of vertices and edges forming a graph • connected component: maximal connected subgraph. E.g., the graph below has 3 connected components.
  • 10. Subgraphs Examples 0 0 0 1 2 0 1 2 1 2 3 1 2 3 G1 (i) (ii) (iii) 3(iv) (a) Some of the subgraph of G1 0 0 0 0 0 1 1 1 1 2 2 2 (i) (ii) (iii) (iv) (b) Some of the subgraph of G3 G3
  • 11. More… • tree - connected graph without cycles • forest - collection of trees tree tree forest tree tree
  • 12. Connectivity • Let n = #vertices, and m = #edges • A complete graph: one in which all pairs of vertices are adjacent • How many total edges in a complete graph? – Each of the n vertices is incident to n-1 edges, however, we would have counted each edge twice! Therefore, intuitively, m = n(n -1)/2. • Therefore, if a graph is not complete, m < n(n -1)/2 n=5 m = (5 ∗ 4)/2 = 10
  • 13. More Connectivity n = #vertices n=5 m = #edges m=4 • For a tree m = n - 1 If m < n - 1, G is not connected n=5 m=3
  • 14. Oriented (Directed) Graph • A graph where edges are directed
  • 15. Directed vs. Undirected Graph • An undirected graph is one in which the pair of vertices in a edge is unordered, (v0, v1) = (v1,v0) • A directed graph is one in which each edge is a directed pair of vertices, <v0, v1> != <v1,v0> tail head
  • 16. ADT for Graph objects: a nonempty set of vertices and a set of undirected edges, where each edge is a pair of vertices functions: for all graph ∈ Graph, v, v1 and v2 ∈ Vertices Graph Create()::=return an empty graph Graph InsertVertex(graph, v)::= return a graph with v inserted. v has no incident edge. Graph InsertEdge(graph, v1,v2)::= return a graph with new edge between v1 and v2 Graph DeleteVertex(graph, v)::= return a graph in which v and all edges incident to it are removed Graph DeleteEdge(graph, v1, v2)::=return a graph in which the edge (v1, v2) is removed Boolean IsEmpty(graph)::= if (graph==empty graph) return TRUE else return FALSE List Adjacent(graph,v)::= return a list of all vertices that are adjacent to v
  • 17. Graph Representations Adjacency Matrix Adjacency Lists
  • 18. Adjacency Matrix Let G=(V,E) be a graph with n vertices. The adjacency matrix of G is a two-dimensional n by n array, say adj_mat If the edge (vi, vj) is in E(G), adj_mat[i][j]=1 If there is no such edge in E(G), adj_mat[i][j]=0 The adjacency matrix for an undirected graph is symmetric; the adjacency matrix for a digraph need not be symmetric
  • 19. Examples for Adjacency Matrix 0 0 4 0 2 1 5 1 2 3 6 3 1 0 1 1 1 0 1 0 1 0 1 1   7   1 0 1 2 0 1 1 0 0 0 0 0 1 1 0 1 0 0 0   1    0 0 1 0 0 0 0  1 1 1 0 1 0 0 1 0 0 0 0 G2   G1 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0   0 0 0 0 1 0 1 0 symmetric 0 0 0 0 0 1 0 1   undirected: n2/2 0  0 0 0 0 0 1 0  directed: n2 G4
  • 20. Merits of Adjacency Matrix From the adjacency matrix, to determine the connection of vertices is easy n −1 The degree of a vertex is ∑ adj _ mat[i][ j ] j=0 For a digraph (= directed graph), the row sum is the out_degree, while the column sum is the in_degree n −1 n −1 ind (vi ) = ∑ A[ j , i ] outd (vi ) = ∑ A[i , j ] j =0 j =0
  • 21. Adjacency Lists (data structures) Each row in adjacency matrix is represented as an adjacency list. #define MAX_VERTICES 50 typedef struct node *node_pointer; typedef struct node { int vertex; struct node *link; }; node_pointer graph[MAX_VERTICES]; int n=0; /* vertices currently in use */
  • 22. 0 0 4 2 1 5 1 2 3 6 3 7 0 1 2 3 0 1 2 1 0 2 3 1 0 3 2 0 1 3 2 0 3 3 0 1 2 3 1 2 G1 0 4 5 5 4 6 0 1 6 5 7 1 0 2 1 7 6 2 G3 G4 2 An undirected graph with n vertices and e edges ==> n head nodes and 2e list nodes
  • 23. Some Operations degree of a vertex in an undirected graph –# of nodes in adjacency list # of edges in a graph –determined in O(n+e) out-degree of a vertex in a directed graph –# of nodes in its adjacency list in-degree of a vertex in a directed graph –traverse the whole data structure
  • 24. Graph Traversal • Problem: Search for a certain node or traverse all nodes in the graph • Depth First Search – Once a possible path is found, continue the search until the end of the path • Breadth First Search – Start several paths at a time, and advance in each one step at a time
  • 25. Depth-First Search A B C D E F G H I J K L M N O P
  • 26. Exploring a Labyrinth Without Getting Lost • A depth-first search (DFS) in an undirected graph G is like wandering in a labyrinth with a string and a can of red paint without getting lost. • We start at vertex s, tying the end of our string to the point and painting s “visited”. Next we label s as our current vertex called u. • Now we travel along an arbitrary edge (u, v). • If edge (u, v) leads us to an already visited vertex v we return to u. • If vertex v is unvisited, we unroll our string and move to v, paint v “visited”, set v as our current vertex, and repeat the previous steps.
  • 27. Breadth-First Search • Like DFS, a Breadth-First Search (BFS) traverses a connected component of a graph, and in doing so defines a spanning tree with several useful properties. • The starting vertex s has level 0, and, as in DFS, defines that point as an “anchor.” • In the first round, the string is unrolled the length of one edge, and all of the edges that are only one edge away from the anchor are visited. • These edges are placed into level 1 • In the second round, all the new edges that can be reached by unrolling the string 2 edges are visited and placed in level 2. • This continues until every vertex has been assigned a level. • The label of any vertex v corresponds to the length of the shortest path from s to v. 27
  • 28. BFS - A Graphical Representation 0 0 1 A B C D A B C D a) E F G H E F G H b) I J K L I J K L M N O P M N O P 0 1 2 0 1 2 3 A B C D B C D A c) d) E F G H E F G H I J K L I J K L M N O P M N 28 O P
  • 29. More BFS 0 1 2 3 0 1 2 3 A B C D A B C D E F G H E F G H 4 4 I J K L I J K L M N O P M N O P 5
  • 30. Applications: Finding a Path • Find path from source vertex s to destination vertex d • Use graph search starting at s and terminating as soon as we reach d – Need to remember edges traversed • Use depth – first search ? • Use breath – first search?
  • 31. DFS vs. BFS F B A start DFS Process E G D C destination C DFS on C D Call DFS on D B DFS on B B B Return to call on B A DFS on A A A A G Call DFS on G found destination - done! D Path is implicitly stored in DFS recursion B Path is: A, B, D, G A
  • 32. DFS vs. BFS F B A start E BFS Process G D C destination rear front rear front rear front rear front A B D C D Initial call to BFS on A Dequeue A Dequeue B Dequeue C Add A to queue Add B Add C, D Nothing to add rear front G found destination - done! Dequeue D Path must be stored separately Add G