chapter 12

Download Chapter 12

If you can't read please download the document

Upload: zwi

Post on 06-Jan-2016

34 views

Category:

Documents


0 download

DESCRIPTION

Chapter 12. Graphs. Chapter Objectives. Learn about graphs Become familiar with the basic terminology of graph theory Discover how to represent graphs in computer memory Explore graphs as ADTs Examine and implement various graph traversal algorithms. Chapter Objectives. - PowerPoint PPT Presentation

TRANSCRIPT

  • Chapter 12Graphs

    Data Structures Using C++

  • Chapter ObjectivesLearn about graphsBecome familiar with the basic terminology of graph theoryDiscover how to represent graphs in computer memoryExplore graphs as ADTsExamine and implement various graph traversal algorithms

    Data Structures Using C++

  • Chapter ObjectivesLearn how to implement the shortest path algorithmExamine and implement the minimal spanning tree algorithmExplore the topological sort

    Data Structures Using C++

  • Knigsberg Bridge ProblemIn 1736, the following problem was posed:

    River Pregel (Pregolya) flows around the island KneiphofDivides into twoRiver has four land areas (A, B,C, D)Bridges are labeled a, b, c, d, e, f, g

    Data Structures Using C++

  • Graphs

    Data Structures Using C++

  • Knigsberg Bridge ProblemThe Knigsberg bridge problem Starting at one land area, is it possible to walk across all the bridges exactly once and return to the starting land area? In 1736, Euler represented Knigsberg bridge problem as graph; Answered the question in the negative. This marked (as recorded) the birth of graph theory.

    Data Structures Using C++

  • Graphs

    Data Structures Using C++

  • Graph Definitions and NotationA graph is a pair G = (V, E), where V is a finite nonempty set, called the set of vertices of G, and E V x VElements of E are pairs of elements of V. E is called the set of edges

    Data Structures Using C++

  • Graph Definitions and NotationLet V(G) denote the set of vertices, and E(G) denote the set of edges of a graph G. If the elements of E(G) are ordered pairs, G is called a directed graph or digraph; Otherwise, G is called an undirected graphIn an undirected graph, the pairs (u, v) and (v, u) represent the same edge

    Data Structures Using C++

  • Various Undirected Graphs

    Data Structures Using C++

  • Various Directed Graphs

    Data Structures Using C++

  • Graph Representation: Adjacency MatrixLet G be a graph with n vertices, where n > 0Let V(G) = {v1, v2, ..., vn}The adjacency matrix AG is a two-dimensional n n matrix such that the (i, j)th entry of AG is 1 if there is an edge from vi to vj; otherwise, the (i, j)th entry is 0

    Data Structures Using C++

  • Graph Representation: Adjacency Matrix

    Data Structures Using C++

  • Graph Representation: Adjacency ListsIn adjacency list representation, corresponding to each vertex, v, is a linked list such that each node of the linked list contains the vertex u, such that (v, u) E(G)Array, A, of size n, such that A[i] is a pointer to the linked list containing the vertices to which vi is adjacentEach node has two components, (vertex and link)Component vertex contains index of vertex adjacent to vertex i

    Data Structures Using C++

  • Graph Representation: Adjacency Matrix

    Data Structures Using C++

  • Graph Representation: Adjacency Matrix

    Data Structures Using C++

  • Operations on GraphsCreate the graph: store in memory using a particular graph representationClear the graph: make the graph emptyDetermine whether the graph is emptyTraverse the graphPrint the graph

    Data Structures Using C++

  • class linkedListGraphtemplateclass linkedListGraph: public linkedListType{public:void getAdjacentVertices(vType adjacencyList[],int& length); //Function to retrieve the vertices adjacent to a given //vertex. //Postcondition: The vertices adjacent to a given vertex // are retrieved in the array adjacencyList. The parameter length specifies the number // of vertices adjacent to a given vertex.};

    Data Structures Using C++

  • class linkedListGraphtemplatevoid linkedListGraph::getAdjacentVertices (vType adjacencyList[], int& length){nodeType *current;length = 0;current = first;

    while(current != NULL){adjacencyList[length++] = current->info;current = current->link;}}

    Data Structures Using C++

  • Graph TraversalsDepth first traversalMark node v as visitedVisit the nodeFor each vertex u adjacent to vIf u is not visitedStart the depth first traversal at u

    Data Structures Using C++

  • Depth First TraversalTraversal: 0 1 2 4 3 5 6 8 10 7 9

    Data Structures Using C++

  • Breadth First TraversalThe general algorithm is:a. for each vertex v in the graphif v is not visitedadd v to the queue //start the breadth // first search at vb. Mark v as visitedc. while the queue is not emptyc.1. Remove vertex u from the queuec.2. Retrieve the vertices adjacent to uc.3. for each vertex w that is adjacent to uif w is not visitedc.3.1. Add w to the queuec.3.2. Mark w as visited

    Data Structures Using C++

  • Breadth First TraversalTraversal: 0 1 5 2 3 6 4 8 10 7 9

    Data Structures Using C++

  • Weighted Graphs

    Data Structures Using C++

  • Shortest Path AlgorithmWeight of the edge: edges connecting two vertices can be assigned a nonnegative real numberWeight of the path P: sum of the weights of all the edges on the path P; Weight of v from u via PShortest path: path with smallest weightShortest path algorithm: greedy algorithm developed by Dijkstra

    Data Structures Using C++

  • Shortest Path AlgorithmLet G be a graph with n vertices, where n > 0. Let V(G) = {v1, v2, ..., vn}. Let W be a two-dimensional n X n matrix such that:

    Data Structures Using C++

  • Shortest PathThe general algorithm is:

    Initialize the array smallestWeight so thatsmallestWeight[u] = weights[vertex, u]Set smallestWeight[vertex] = 0Find the vertex, v, that is closest to vertex for which the shortest path has not been determinedMark v as the (next) vertex for which the smallest weight is foundFor each vertex w in G, such that the shortest path from vertex to w has not been determined and an edge (v, w) exists, if the weight of the path to w via v is smaller than its current weight, update the weight of w to the weight of v + the weight of the edge (v, w)

    Because there are n vertices, repeat steps 3 through 5 n 1 times

    Data Structures Using C++

  • Shortest Path

    Data Structures Using C++

  • Shortest Path

    Data Structures Using C++

  • Shortest Path

    Data Structures Using C++

  • Shortest Path (end result)

    Data Structures Using C++

  • Minimal Spanning TreeThis graph represents the airline connections of a company between seven cities (cost factor shown)

    Data Structures Using C++

  • Minimal Spanning TreeCompany needs to shut down the maximum number of connections and still be able to fly from one city to another (may not be directly).

    Data Structures Using C++

  • Minimal Spanning Tree(Free) tree T : simple graph such that if u and v are two vertices in T, then there is a unique path from u to vRooted tree: tree in which a particular vertex is designated as a rootWeighted tree: tree in which weight is assigned to the edges in TIf T is a weighted tree, the weight of T, denoted by W(T ), is the sum of the weights of all the edges in T

    Data Structures Using C++

  • Minimal Spanning TreeA tree T is called a spanning tree of graph G if T is a subgraph of G such that V(T ) = V(G), All the vertices of G are in T.

    Data Structures Using C++

  • Minimal Spanning TreeTheorem: A graph G has a spanning tree if and only if G is connected.In order to determine a spanning tree of a graph, the graph must be connected.Let G be a weighted graph. A minimal spanning tree of G is a spanning tree with the minimum weight.

    Data Structures Using C++

  • Prims AlgorithmBuilds tree iteratively by adding edges until minimal spanning tree obtainedStart with a source vertexAt each iteration, new edge that does not complete a cycle is added to tree

    Data Structures Using C++

  • Prims AlgorithmGeneral form of Prims algorithm (let n = number of vertices in G):

    1. Set V(T) = {source}2. Set E(T) = empty3. for i = 1 to n 3.1 minWeight = infinity;3.2 for j = 1 to n if vj is in V(T)for k = 1 to n if vk is not in T and weight[vj][vk] < minWeight { endVertex = vk; edge = (vj, vk); minWeight = weight[vj][vk]; } 3.3 V(T) = V(T) {endVertex}; 3.4 E(T) = E(T) {edge};

    Data Structures Using C++

  • Prims Algorithm

    Data Structures Using C++

  • Prims Algorithm

    Data Structures Using C++

  • Prims Algorithm

    Data Structures Using C++

  • Prims Algorithm

    Data Structures Using C++

  • Prims Algorithm (end result)

    Data Structures Using C++

  • Precedence GraphNodes represent events, directed edges represent precedencesEvent 0 must precede 1 and 5, 3 must be preceded by 1, 4, and 7, etc.

    Data Structures Using C++

  • Topological OrderLet G be a directed graph and V(G) = {v1, v2, ..., vn}, where n > 0. A topological ordering of V(G) is a linear ordering vi1, vi2, ..., vin of the vertices such that if vij is a predecessor of vik, j k, 1
  • Topological OrderBecause the graph has no cycles:There exists a vertex u in G such that u has no predecessor.There exists a vertex v in G such that v has no successor.

    Data Structures Using C++

  • Breadth First Topological OrderCreate the array predCount and initialize it so that predCount[i] is the number of predecessors of the vertex viInitialize the queue, say queue, to all those vertices vk so that predCount[k] is zero. (Because the graph has no cycles, queue is never empty until all nodes have gone through it.)

    Data Structures Using C++

  • Breadth First Topological Order3.while the queue is not emptyRemove the front element, u, of the queuePut u in the next available position, say topologicalOrder[topIndex], and increment topIndexFor all the immediate successors w of uDecrement the predecessor count of w by 1if the predecessor count of w is zero, add w to queue

    Data Structures Using C++

  • Breadth First Topological Order

    Data Structures Using C++

  • Breadth First Topological Order

    Data Structures Using C++

  • Breadth First Topological Order

    Data Structures Using C++

  • Breadth First Topological Order (end result)

    Data Structures Using C++

  • Chapter SummaryGraphsGraphs as ADTsTraversal algorithmsShortest path algorithmsMinimal spanning treesTopological sort

    Data Structures Using C++