Docstoc

Graphs

Document Sample
Graphs Powered By Docstoc
					Graphs



Part 5: Chapter 17 Sedgewick




               Graphs          1
Graph
 Many problems require
   a collection of items (i.e. a set)
   relationships/connections between items
 Examples:
   maps: items are cities, connections are roads
   scheduling: items are tasks, connections are
    dependencies
   networks: items are sites, connections are
    routes
   programs: items are functions, connections are
    calls

                       Graphs                        2
…Graphs
 A graph G = (V,E)
   V is a set of vertices
   E is a set of edges (subset of V×V)
 Example:




                       Graphs             3
                A real example:
              Australian road distances
Dist   Adel    Bris   Can      Dar    Melb   Perth Syd

Adel   -       2055   1390     3051   732    2716   1605

Bris   2055    -      1291     3429   1671   4771   982

Can    1390    1291   -        4441   658    4106   309

Dar    3051    3429   4441     -      3783   4049   4411

Melb   732     1671   658      3783   -      3448   873

Perth 2716     4771   4106     4049   3448   -      3972

Syd    1605    982    309      4411   873    3972   -

                            Graphs                         4
…Example: Australian Roads




             Graphs          5
Simple Graph
 A simple graph has no parallel edges
   ie. It has at most one edge connecting any two
  vertices
 A simple graph has no self loops
   ie no edges from a vertex to itself


 In this course, when we refer to a graph, we
  mean a simple graph unless stated otherwise.



                        Graphs                       6
Graph Properties
 A graph with V vertices
   has at most V(V-1)/2 edges.
     e.g. E ≤ V(V-1)/2


 The ratio V:E can vary considerably.
   if E is closer to V2, the graph is dense
   if E is closer to V, the graph is sparse




                      Graphs                   7
…Graph Properties
 Knowing whether a graph is sparse or dense is
  important
   may affect choice of data structures to represent
    graph
   may affect choice of algorithms to process graph




                        Graphs                      8
…Graph Terminology
 Complete graph
   there is an edge from each vertex to every other
    vertex
   in a complete graph, E = V(V-1)/2




                       Graphs                      9
…Graph Terminology
   Tree: connected (sub)graph with no cycles
   Spanning tree: tree containing all vertices
   Clique: complete subgraph
   Consider the following single graph:




                        Graphs                    10
Graph Terminology
 Graph
   set of vertices V (e.g. {1, 2, 3, 4, 5})
   set of edges E, involving all of V (e.g. {1-2, 2-
    3, 2-4, 3-5})


 Subgraph
   subset of edges E' (e.g. {1-2, 2-4})
   all vertices involved in edges from E' (e.g. {1,
    2, 4})



                        Graphs                         11
…Graph Terminology
 Induced subgraph
   subset of vertices V' (e.g. {1, 2, 3, 5})
   all edges involving a pair from V' (e.g. {1-2, 2-
    3, 3-5})
 If |E| = 0, then we have a set.




                        Graphs                      12
…Graph Terminology
 Adjacency:
   A vertex is adjacent to a second vertex if there
    is an edge that connects them
 Degree:
   The degree of a vertex is the number of edges
    from v

 Path: a sequence of edges where
   vertex at end of one edge starts another edge

 Cycle: a path where
   last vertex in path is same as first vertex in path

                         Graphs                        13
Paths and Cycles




              Graphs   14
…Graph Terminology
 Simple Path
   The vertices and the edges are distinct


 Connected graph
   there is a path from each vertex to every other
    vertex
   if a graph is not connected, it has connected
    components




                        Graphs                        15
…Graph Terminology
 Hamilton path
   A simple path that
    connects two
    vertices that visits
    every vertex in the
    graph exactly once

   If the path is from
    a vertex back to
    itself it is called a
    hamilton tour

                            Graphs   16
…Graph Terminology
 Euler path
                                         B
   A path the connects
    two vertices using
    each edge in the                 A       C
    path exactly once.

   If the path is from
    a vertex back to
                                     E       D
    itself it is an euler
    tour


                            Graphs               17
           Exercise:
Does this have a hamilton path?




              Graphs              18
              Exercise:
    Does this have an euler path?
 A graph has an Euler
  path if and only if it
  is connected and
  exactly 2 vertices
                                A   B
  are of odd degree

 A graph has an Euler
  tour if and only if it        D   C
  is connected and all
  vertices are of even
  degree
                       Graphs           19
Undirected vs Directed Graphs
 Undirected graph
   edge(u,v) = edge(v,u),
   no self-loops (i.e. no edge(v,v))
 Directed graph
   edge(u,v) ≠ edge(v,u),
   can have self-loops (i.e. edge(v,v))

 Unless specified, we assume graphs are
  undirected in this course.

                      Graphs               20
…Undirected vs Directed Graphs




             Graphs          21
Other types of Graphs
 Weighted graph
   each edge has an associated value (weight)
   e.g. road map (weights on edges are distances
    between cities)

 Multi-graph
   allow multiple edges between two vertices
   e.g. function call graph (f() calls g() in several
    places)
   eg. Transport – may be able to get to new
    location by bus or train or ferry etc…


                         Graphs                      22
Defining Graphs
 need some way of identifying vertices
   could give diagram showing edges and vertices
   could give a list of edges
 Eg 4 representations of the same graph




                       Graphs                       23
Graph ADT
 Data:
   set of edges, set of vertices

 Operations:
   building: create graph, create edge, add
    edge
   deleting: remove edge, drop whole graph
   scanning: get edges, copy, show



                       Graphs                  24
            Interface for
  (undirected, unweighted) graphs
// vertices denoted by integers 0..N-1
typedef int Vertex;

// edges are pairs of vertices (end-points)
typedef struct {
    Vertex v;
    Vertex w;
} Edge;

Edge mkEdge(Vertex, Vertex);
// graph representation is hidden
typedef struct graphRep *Graph;



                       Graphs                 25
…Interface
// operations on graphs
Graph newGraph(int nV); // #vertices
void insertE(Graph g, Edge e);
void removeE(Graph g, Edge e);

// returns #vertices & array of edges int
int edges(Edge es[], int nE, Graph g);

Graph copy(Graph g);
void destroy(Graph g);
void show(Graph g);

                   Graphs                   26
Adjacency Matrix Representation

                         Edges
                          represented
                          by a VxV
                          boolean
                          matrix




               Graphs               27
  Adjacency Matrix Representation
          Implementation
typedef struct graphRep GraphRep;
struct graphRep {
    int nV; // #vertices
    int nE; // #edges
    int **edges; // matrix of booleans (0 or 1)
};




                          Graphs                  28
 …Adjacency Matrix Representation
         Implementation
Graph newGraph(int nV) {
    assert(nV >= 0);
    int i, j;
    Graph g = malloc(sizeof(GraphRep));
    assert(g != NULL);
    g->edges = malloc(nV * sizeof(int *));
    assert(g->edges != NULL);
    for (i = 0; i < nV; i++) {
        g->edges[i] = malloc(nV * sizeof(int));
        assert(g->edges[i] != NULL);
        for (j = 0; j < nV; j++) g->edges[i][j] = 0;
    }
    g->nV = nV;
    g->nE = 0;
    return g;
}
                          Graphs                       29
 …Adjacency Matrix Representation
         Implementation
// local checking function. Checks if vertex v
// is in the graph
static int validV(Graph g, Vertex v) {
    return (v >= 0 && v < g->nV);
}

// Create an edge from v to w
// Does not allow self loops
Edge mkEdge(Vertex v, Vertex w) {
    assert(v >= 0 && w >= 0 && v != w);
    Edge e = {v,w};
    return e;
}


                       Graphs                    30
…Adjacency Matrix Implementation
//Insert an edge into a graph
void insertE(Graph g, Edge e) {
    assert(g != NULL && validV(g,e.v)
                     && validV(g,e.w));
    if (g->edges[e.v][e.w])
        return;
    g->edges[e.v][e.w] = 1;
    g->edges[e.w][e.v] = 1;
    g->nE++;
}




                        Graphs            31
…Adjacency Matrix Implementation
// remove an edge from a graph
void removeE(Graph g, Edge e) {
   assert(g != NULL && validV(g,e.v)
                    && validV(g,e.w));
   if (!g->edges[e.v][e.w])
       return;
   g->edges[e.v][e.w] = 0;
   g->edges[e.w][e.v] = 0;
   g->nE--;
}



                       Graphs            32
…Adjacency Matrix Implementation
void show(Graph g) {
    assert(g != NULL);
    printf("V=%d, E=%d\n", g->nV, g->nE);
    int i, j;
    for (i = 0; i < g->nV; i++) {
        int nshown = 0;
        for (j = 0; j < g->nV; j++) {
            if (g->edges[i][j] != 0) {
                printf("%d-%d ",i,j);
                nshown++;
            }
        }
        if (nshown > 0) printf("\n");
    }
}
                         Graphs             33
…Adjacency Matrix Implementation
 int edges(Edge es[], int nE, Graph g) {
     assert(g != NULL && es != NULL && nE > 0);
     int i, j, n = 0;
     for (i = 0; i < g->nV; i++) {
         for (j = i+1; j < g->nV; j++) {
             if (g->edges[i][j] != 0) {
                 assert(n < nE);
                 es[n++] = mkEdge(i,j);
             }
         }
     }
     return n;
}
                          Graphs                  34
Adjacency Matrix Representation
 Storage cost: V int ptrs + V2 ints
 If the graph is sparse, most storage is wasted.
   A storage optimisation: store only top-right
      part of matrix.




                       Graphs                   35
Adjacency List Representation
 For each vertex, store
  linked list of adjacent
  vertices




                            Graphs   36
Adjacency List Implementation




              Graphs            37
Adjacency List Implementation
typedef struct vNode *VList;
struct vNode {
    Vertex v;
    VList next;
};
typedef struct graphRep GraphRep;
struct graphRep {
    int nV; // #vertices
    int nE; // #edges VList
    VList *edges; // array of lists
};

                       Graphs         38
Adjacency List Implementation
Graph newGraph(int nV) {
    int i;
    Graph g = malloc(sizeof(GraphRep));
    assert(g != NULL);
    VList *e = malloc(nV * sizeof(VList));
    assert(e != NULL);
    for (i = 0; i < nV; i++)
        e[i] = NULL;
    g->nV = nV;
    g->nE = 0;
    g->edges = e;
    return g;
}
                       Graphs                39
…Adjacency List Implementation
// Does not allow self-loops
Edge mkEdge(Vertex v, Vertex w) {
    assert(v >= 0 && w >= 0 && v != w);
    Edge e = {v,w};
    return e;
}

//Does not check for parallel edges
void insertE(Graph g, Edge e) {
   assert(g != NULL && e.v < g->nV && e.w < g->nV);
   g->edges[e.v] = insertVList(e.w,g->edges[e.v]);
   g->edges[e.w] = insertVList(e.v,g->edges[e.w]);
   g->nE++;
}
                        Graphs                   40
…Adjacency List Implementation
void show(Graph g) {
    assert(g != NULL);
    printf("V=%d, E=%d\n", g->nV, g->nE);
    int i;
    for (i = 0; i < g->nV; i++) {
        VList n = g->edges[i];
        while (n != NULL) {
            printf("%d-%d ",i,n->v);
            n = n->next;
        }
        if (g->edges[i] != NULL)
            printf("\n");
        }
}
                        Graphs              41
Implementation Comparison

Property      Adjacency     Adjacency
              Matrix        List
Space         V2            V+E
Initialise    V2            V
Insert Edge   1             1
Find/Remove   1             V
Edge

                   Graphs               42

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:4
posted:12/1/2011
language:English
pages:42