Tremblay Chap 19

download Tremblay Chap 19

of 106

Transcript of Tremblay Chap 19

  • 8/12/2019 Tremblay Chap 19

    1/106

    Data Structures and Software Development in anObject-Oriented Domain

    Java Edition

    Jean-Paul Tremblay and Grant A. ChestonUniversity of Saskatchewan

    ccopyright 2008 J.P. Tremblay and G.A. Cheston

  • 8/12/2019 Tremblay Chap 19

    2/106

    Chapter 19

    Graphs

    Contents

    19.1 Introduction and Examples of Graph Modeling . . . . . . . 842

    19.2 Basic Definitions of Graph Theory . . . . . . . . . . . . . . . 849

    19.3 Graph ADT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855

    19.4 Paths, Reachability, and Connectedness . . . . . . . . . . . . 861

    19.5 Graph Representations . . . . . . . . . . . . . . . . . . . . . . 865

    19.5.1 Adjacency Matrix Representation . . . . . . . . . . . . . . . 879

    19.5.2 Adjacency Lists Representation . . . . . . . . . . . . . . . . 886

    19.5.3 Searchable Graph . . . . . . . . . . . . . . . . . . . . . . . . 887

    19.6 Computing Paths from a Matrix Representation of Graphs 895

    19.6.1 Computing Reachability, Using Matrix Multiplications . . . 895

    19.6.2 Efficient Reachability Algorithm . . . . . . . . . . . . . . . . 897

    19.6.3 All Pairs Shortest Paths Algorithm . . . . . . . . . . . . . . 900

    19.6.4 Single Source Shortest Paths Algorithm . . . . . . . . . . . . 903

    19.7 Traversals of Undirected Graphs . . . . . . . . . . . . . . . . 909

    19.7.1 Breadth-First Search . . . . . . . . . . . . . . . . . . . . . . 909

    19.7.2 Depth-First Search . . . . . . . . . . . . . . . . . . . . . . . 914

    19.8 Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 921

    19.8.1 Connectivity and Components . . . . . . . . . . . . . . . . . 92219.8.2 Spanning Trees . . . . . . . . . . . . . . . . . . . . . . . . . . 924

    19.8.3 Top ological Sorting . . . . . . . . . . . . . . . . . . . . . . . 928

    19.8.4 Scheduling Networks . . . . . . . . . . . . . . . . . . . . . . . 932

    19.8.5 Graphs in Testing . . . . . . . . . . . . . . . . . . . . . . . . 938

    19.9 Concluding Remarks . . . . . . . . . . . . . . . . . . . . . . . . 944

    The data structure introduced in this chapter, the graph, is a generalization of the treedata structure. It is similar to a tree in that a graph consists of a set of nodes and a setof lines with each line joining a pair of nodes. In a tree, the lines are used to define ahierarchical structure (i.e., a node has one parent and may have several children). This isnot true in a graph where a node is simply joined to a number of other nodes by lines.

    Figure 19.1 shows two graphs. In the left graph, there is a direction associated with eachline, as indicated by a directed arrowhead; such a graph is called directed. In the rightgraph, the lines have no direction, and the graph is called undirected. Usually, a graph iseither directed or undirected, although sometimes a graph has both directed and undirectedlines.

    841

  • 8/12/2019 Tremblay Chap 19

    3/106

    842 Graphs

    1

    2

    3

    4

    5

    a

    bc

    d

    e f

    Figure 19.1. Examples of directed and undirected graphs

    Graphs have been found to be useful in a wide variety of application areas. To someextent, each area has developed its own notation. For example, sometimes the nodes arecalled verticesor points. Also, the lines can be calledarcsor edges. Often, we say that anundirected graph consists of vertices and edges and a directed graph consists of nodes andarcs. Either or both of the vertices and edges may be labeled with letters, numbers, or someother identification.

    Section 19.1 will present the use of graphs in a number of applications. In discussingthese applications, a number of graph terms will be informally introduced. Sections 19.2and 19.3 will present more formal views of graphs, first through more precise definitions ofgraph terms and through an Abstract Data Type (ADT) specification.

    Many interesting properties of graphs are related to paths in graphs. Section 19.4presents some basic path concepts. There are two standard representations for a graphwithin a program; these will be described in Section 19.5. The next two sections presenta number of graph algorithms. Section 19.6 develops algorithms for computing paths ina graph. Section 19.7 presents the two standard traversals of a graph: breadth first anddepth first. Finally, in Section 19.8, the details and algorithms are presented for a numberof graph applications, including connected components, network scheduling, and softwaretesting using graphs.

    19.1 Introduction and Examples of Graph Modeling

    Graphs are used widely to model problems in many different application areas. Constructinga model is essentially a process of deciding what features or aspects of a real-world problemor application are to be represented for the current analysis or study. The model of anapplication varies widely depending on the view or purpose that a modeler has for theapplication. Good models capture the essence of the real world that is relevant to thecurrent problem and ignore the details irrelevant to this problem. Moreover, good modelsare robust; that is, they have the ability to remain relevant as the applications evolve.

    This section outlines several problems to which graph theory has been applied success-fully. Although many problems could have been chosen, the ones presented in this sectionillustrate the diversity of application areas that can be modeled with graph structures. One

    of the objectives of this section is to get an intuitive idea of a graph by looking at thediagrams of several graphs.

    A glance at the next few pages shows several graphs. Although several of the graphshave somewhat different structures, note that every diagram consists of a set of vertices

  • 8/12/2019 Tremblay Chap 19

    4/106

    Sec. 19.1. Introduction and Examples of Graph Modeling 843

    Calgary

    Edmonton

    Victoria

    Vancouver

    Prince George

    Saskatoon

    Regina

    Winnipeg

    Prince Albert

    150

    806

    638

    1245 292

    597

    526

    612

    765258

    578

    843

    160

    1056

    Figure 19.2. A graph of major highway arteries in Western Canada

    (nodes, points). These are shown as circles, ovals, small dots, or other icons. The verticesare sometimes unlabeled, whereas others are labeled by letters, numbers, or other strings.Also, in every diagram certain pairs of vertices are joined by lines. These lines are moreoften called edges or arcs. The other details, such as the positions of the vertices, the shapeor length of the edges, and so on, are of no importance at present. Notice that every edge

    starts at one vertex and ends at another vertex. If the edge has a specific direction, asindicated by an arrowhead, it is called directed. Otherwise, it is called undirected. A formaldefinition of the graph, which is essentially an abstract mathematical system, will be givenin the next section.

    The preceding informal definition of a graph contains no reference to the length, shape,and positioning of the edge joining any pair of vertices, nor does it prescribe any ordering ofthe positions of the vertices. Therefore, for a given graph, there is no unique diagram whichrepresents the graph, and it can happen that two diagrams that look entirely different mayrepresent the same graph.

    Example 19.1 One of the most frequent uses of a graph occurs when you plan a vacation. Iftravel is by car, road maps represent the possible roadway systems that can be used for thetrip. A road map is actually a model of the main highways for travel purposes. Also, a roadmap is a graph where the vertices are the towns and cities in some geographical area, and

    the edges represent the roads joining these cities or towns.Figure 19.2 shows a graph of the main highway arteries joining the major cities in WesternCanada. Each edge or road in the graph allows travel in either direction, so the edges areundirected. The label a number associated with each edge denotes the distance inkilometers between the two cities. When planning a trip, a traveler may be interested inthe distance between two cities by using some particular route (e.g., between Winnipeg andVictoria via Edmonton). Because of time constraints, a traveler may also be interested inthe minimum distance between two given cities.

    Example 19.2 The computer simulation of traffic systems is a tool frequently used by transporta-tion and city planners. The systems modeled range from the traffic network across a nation,a city, an area of a city, or even the traffic flow on one bridge or in one intersection. Themodels are used to pinpoint present or future bottlenecks and to suggest and test proposedchanges.

    In a city, the street system can be modeled as a graph where the intersections are representedas vertices, and the street segments between intersections are the edges. For example, see thestreet system of Figure 19.3a and the graph of Figure 19.3b. Two-way streets are representedas undirected edges (i.e., edges without an arrowhead, whereas one-way streets are directededges). One of the applications of such a graph includes the determination of the shortest

  • 8/12/2019 Tremblay Chap 19

    5/106

    844 Graphs

    (b)(a)

    Figure 19.3. A graphic representation of a city street system

    path that the police and fire departments would use to answer a 911 call. Note that the edgescould be labeled with street names, traffic densities, and so on.

    Example 19.3 A more recent use of graphs has been in the modeling of computer networks. Acomputer network typically consists of a variety of elements such as computers and commu-nication lines. In a graph representation of a computer network, each vertex is a device suchas a computer or terminal, and each edge or link denotes a communication medium such asa telephone line or communication cable. Many industrial firms and universities have oneor more local area networks that typically cover an area less than one square kilometer. In

    addition, there are long-haul or wide-area networks whose vertices, from a geographicviewpoint, can be located in one or more countries. Graphs are important in modeling thesenetworks with respect to reliability and efficiency.

    A graph representation of a computer network appears in Figure 19.4. The subnet partof the network represents the communication part of the network. The devices around thecommunications subnet can be viewed as external devices. Although we have taken theliberty of representing terminals and personal computers by icons, it should be emphasizedthat in an abstract graph these components would be simple nodes. The arrangement ofsubnet vertices (nodes) and links in the subnet is not arbitrary. In a local area network, thesubnet nodes are often arranged as a ring or star structure (see Figure 19.5). In wide-areanetworks, subnet nodes can be far apart and arranged in somewhat arbitrary ways.

    Example 19.4 Most software products consist of modules that invoke each other. From an object-oriented perspective, a module might be a method or a whole class. A call graphrepresents

    modules by nodes. A directed line from a nodex to a nodey indicates thatxinvokesy. In thecall graph of Figure 19.6, for example, module A invokes modules B , C, and D. Modules Band C invoke module E. When one module invokes another, there must be communicationbetween the two modules through an interface. An interface usually consists of a list ofparameters. Some researchers have attempted to use graphs to evaluate the overall qualityof a software system by modeling the system with an extended call graph that shows themodule interfaces.

    Example 19.5 There are several applications in computer science where it is convenient to model,or represent, an algorithm by a graph. An example of such an application arises in the contextof generating test cases for an algorithm. These tests are derived by analyzing the structure ofthe algorithm with respect to control flow. The control flow is modeled by a flow graph. Eachvertex in a flow graph represents one or more statements or instructions that do not involvebranching. Thus, a sequence of statements preceding a conditional statement is mapped into

    a single vertex. The arcs (directed edges) in the flow graph represent the flow of control.Any module specified in a procedural or object-oriented language can be translated into aflow graph. For example, Figure 19.7 shows the flow-graph representations of certain familiarconstructs that are available in many languages. The label T on an edge denotes a truebranch, whereas F denotes a false branch.

  • 8/12/2019 Tremblay Chap 19

    6/106

    Sec. 19.1. Introduction and Examples of Graph Modeling 845

    Terminal

    CPU

    Personal computer

    Subnet

    Figure 19.4. Graph representation of a computer network

    (a) Ring arrangement (b) Star arrangement

    Figure 19.5. Specialized node arrangements in local area networks

    As an example, Figure 19.8b shows the flow graph for the skeleton of a module in Figure 19.8a.Note that vertex 11 was created to represent statements after the outer

    , although there arenot any of them. The statementss1 throughs9 in Figure 19.8a are assumed to be noncontrolstatements, such as assignment statements.

    One testing approach is to use the flow graph of a module to generate a set of independentpaths that must be executed in order to ensure that every statement and branch has beenexecuted at least once, which will be discussed in Section 19.8.5 later in this chapter.

    Example 19.6 One of the first computerized applications of graphs was concerned with projectscheduling. The objective of scheduling a project is to schedule the completion of a number

  • 8/12/2019 Tremblay Chap 19

    7/106

    846 Graphs

    E F G

    CB D

    A

    Figure 19.6. A graph representation of a software system

    Sequence If-then-else

    T F

    While

    T

    F

    Switch

    Figure 19.7. Flow graph notation for various constructs

    of subtasks, calledactivities, so that the overall project can be completed as soon as possible.This is complicated by timing interrelationships between the activities. In most cases, thework on an activity can proceed independently of the progress of the work on many ofthe other activities. However, usually the work on an activity cannot be started until certainspecific activities are completed. These timing considerations need to be analyzed to completethe project in the minimum time. The projects involved might be as simple as the erection ofa house, but tend to be very complex, such as the design and construction of a power dam orthe space race to be first on the moon. The techniques here were instrumental in the United

    States of America, being able to put men on the moon as soon as they were.To illustrate project management concepts, we will first consider scheduling a moderate-sizedsoftware project. Rather than a specific project, the example given will be for an artificialproject. It will be assumed to be a project with three subsystems, as well as a significantuser interface and p ersistent storage interface. It is also assumed that the total project willrequire about 8 months in personnel time. The actual time from start to end will b e less thanthis as several people may be working on the project at the same time. Two of the objectivesof doing the scheduling are to determine what needs to be done in parallel and where thebottlenecks are that need to be completed in the minimum time.

    The completion of a large project involves breaking the project into a set of interrelatedactivities or tasks. For our software project, the resulting activities are shown in the secondcolumn of Table 19.1. The project begins with the activity to identify the objectives (i.e., ageneral specification of what the project is to involve). Early in the project, the personnelwho will use the software product must be consulted. Thus, interviews are scheduled with

    users and managers who will be involved with the operation of the system. Obviously,general objectives of the project must be identified before the interviews. As a result, inthe Preceding Activities column of Table 19.1, activity a1, identify the project, is given asa preceding activity for activities a2 and a3. The fourth activity shows writing an initialdraft of the requirements for the project. This activity has two preceding activities those

  • 8/12/2019 Tremblay Chap 19

    8/106

    Sec. 19.1. Introduction and Examples of Graph Modeling 847

    12

    while (!finished)

    end of loop statement

    end of procedure

    T

    s3

    s4, s6 s7

    s8

    3

    4

    7

    10

    8 96

    11

    F

    T

    TF

    2

    F

    s2

    1 s1

    5

    s9

    flag1 == 0

    flag2 == 0

    (a) (b)

    voidwhatever(){

    s1s2while (!finished){

    s3if (flag1 == 0){

    s4s5

    }else

    {if (flag2 == 0)

    s6else

    s7s8

    }}s9

    }

    s5

    Figure 19.8. Modeling a module with a flow graph

    involving interviews with users and managers. The remaining activities in the table mostlyfollow the steps for developing a software product and so should be easy to follow. Of course,to schedule the timing of the project, time estimates are needed. Thus, the fourth column inTable 19.1 contains an estimate in days for the duration of each activity.

    The creation of a table for a project, such as that given in Table 19.1, can be a nontrivialtask for medium-sized projects. However, for large projects, the task can be formidable. Theidentification of detailed activities and the associated precedence requirements are based onexperience, art, and the current practice in the industry. However, the extent to whichscheduling is useful depends upon modeling the project by identifying meaningful activitiesand precedence requirements, and accurately estimating time duration to complete eachactivity.

    A graph with directed edges is a natural way of describing, representing, and analyzingthe timing interrelationships between the activities. The scheduling of a project can be

    represented by a simple directed graph called a scheduling network, in which the activitiesbecome the edges of the graph. The nodes of the graph are used to coordinate the timing ofactivities. Thus, a node called an event in scheduling terminology represents the stateof the project at a certain time. More specifically, an event represents the requirement thatcertain activities (the incoming edges) must be completed before other activities (the outgoing

  • 8/12/2019 Tremblay Chap 19

    9/106

    848 Graphs

    Table 19.1. Software Project ActivitiesEdge Activity Preceding Estimated

    Activities Duration

    a1 Identify the project 2a2 Initially interview users {a1} 3a3 Initially interview managers {a1} 2a4 Draft initial requirements {a2, a3} 4a5 Identify system boundary and main use cases {a4} 4a6 Review draft of requirements with users {a5} 3a7 Review draft of requirements with managers {a5} 2a8 Consult with external experts {a5} 3a9 Generate requirements document {a6, a7, a8} 10a10 Identify further use cases {a9} 3a11 Identify main objects and classes {a10} 5a12 Design system testing {a9} 5a13 Develop sequence diagrams and partial class diagrams {a11} 8

    for main use cases

    a14 Develop subsystems {a13} 2a15 Develop basic system architecture {a14} 2a16 Develop sequence diagrams and partial class {a15} 4

    diagrams for subsystem 1a17 Develop sequence diagrams and partial class {a15} 6

    diagrams for subsystem 2a18 Develop sequence diagrams and partial class {a15} 5

    diagrams for subsystem 3a19 Refine subsystem organization and system architecture {a16, a17, a18} 3a20 Perform detailed design of users interfaces {a19} 5a21 Implement users interfaces {a20} 15a22 Test users interfaces {a21} 6a23 Evaluate and refine interfaces {a22} 6a24 Design persistent storage interfaces {a19} 4

    a25 Implement persistent storage interfaces {a24} 10a26 Test persistent storage interfaces {a25} 4a27 Subsystem 1 - design {a19} 4a28 - implementation {a27} 10a29 - testing {a28} 3a30 Subsystem 2 - design {a19} 8a31 - implementation {a30} 15a32 - testing {a31} 6a33 Subsystem 3 - design {a19} 6a34 - implementation {a33} 12a35 - testing {a34} 4a36 Systems integration {a23, a29, a32, a35, a26} 6a37 Integration testing {a36} 4a38 Review for quality {a37} 6

    a39 Restructure and revise system for quality {a38} 8a40 System testing {a12, a39} 10

  • 8/12/2019 Tremblay Chap 19

    10/106

    Sec. 19.2. Basic Definitions of Graph Theory 849

    edges) can be started. The graph obtained for Table 19.1 is given in Figure 19.9. The activitya1 has no preceding activities, so it can be started at any time. This is represented by node1 with no incoming edges and an edge for a1 outgoing. Activitiesa2 and a3 require that a1has been completed; hence, their corresponding edges start at node 2. Moving on to consideractivitya4, it requires that a2 and a3 have been completed. Ifa2 and a3 were to have thesame ending node, this would result in two edges between a pair of nodes. Such edges arecalled parallel and create complications. To avoid these complications, a2 is directed intonode 3 and a3 directed into node 4, and two artificial activities are created from node 3 tonode 5 and from node 4 to node 5. In the graph, these artificial activities are given labels d1and d2 to reflect that they are artificial or dummy activities. Each dummy activity is givena duration of zero to reflect that it is only used for synchronization and does not require anytime.

    Similarly, the rest of the events and activities are created as necessary and added to thegraph. Dummy activities are needed to avoid having the edges for activitiesa6, a7, and a8become parallel edges, and also for activitiesa16,a17, anda18. For convenience, the events arenumbered sequentially. Finally, note that each edge is labeled with a number that representsthe duration of the activity. The artificial activities are given duration zero, since they arenot real activities that require time to complete.

    In a directed graph, a vertex with no incoming edges is called a source, and a vertex withno outgoing edges is called a sink. In a scheduling graph for a project, there is exactly one

    source and exactly one sink.An important use of the graph of a project is to determine the earliest completion time forthe project. This time is determined by a sequence of activities such that the activities mustbe done sequentially, and the total duration of the sequence is at least as long as any othersuch sequence. Such a sequence is called a critical path. It is a path (sequence of edges)from the source to the sink such that if any activity on the path is delayed by an amountt,the entire project is delayed by t. A critical path for the graph in Figure 19.9 is shown withdouble lines. It consists of 22 nonzero activities with an earliest completion time of 120 days.In fact, there are two critical paths in this network, as activitya8 can be replaced by activitya6 and still have a path of longest duration. A delay in the completion of any activity on anycritical path will result in a delay in completing the project.

    If the objective is to reduce the earliest completion time for the project, it is necessary to findand speed up at least one activity on every critical path. Since in practice for large graphsthe number of activities that lie on a critical path is a small percentage of the total number

    of activities, say, 10%, only that 10% needs to be considered for speeding up the project.Of course, if the current critical paths are shortened too much, some other path will becomecritical, and it too must be shortened to make the earliest completion time any sooner.

    19.2 Basic Definitions of Graph Theory

    The application of graph theory to many fields has resulted in a great diversity in terminol-ogy. Different authors often use different terms for the same concept, and, what is worse,the same term for different concepts. We will use computer science notation, and, wher-ever possible, we shall indicate the common alternatives used in the literature of computerscience.

    In this section, we shall define a graph as an abstract mathematical system. However,

    to provide some explanation for the terminology used and also to develop some intuition forthe concept of a graph, we shall represent graphs diagrammatically. Any such diagram willalso be called a graph. Alternative methods of representing graphs, suitable for computerrepresentation, will be discussed in Section 19.5.

  • 8/12/2019 Tremblay Chap 19

    11/106

    a1

    1a3

    a4 a5 a7 d4 a9 a10 a11

    a2 d1

    d2 a8

    a6 d3

    d5

    2

    3

    5 6 7 9 11 12 13

    8

    4 10

    21 22 30 31 34 35 36

    a36 a37 a38a17 d7 a19

    a16

    a18 d8

    d6

    1917

    32 33

    26 27

    28 29

    23 24 25

    a23

    a22a21

    a20

    a30 a31 a32

    a28a29

    a25

    a34

    a35

    a15

    a26

    a33

    a24

    a27

    2

    3

    2 0

    0

    4 4

    3

    3 0

    0

    10 3

    2

    5

    4

    5

    3

    4

    6

    8

    4

    515

    10

    15

    12

    10

    6

    6

    3

    6

    4

    4

    6 4 6

    2 0

    0

    0

    0

    6

    Figure 19.9. A scheduling network for a moderate-sized software proj

  • 8/12/2019 Tremblay Chap 19

    12/106

    Sec. 19.2. Basic Definitions of Graph Theory 851

    2

    1

    3

    e1 e3

    e2

    (a) Directed graph with edge labels (b) Undirected graph with edge labels

    (c) Directed graph without edge labels

    2

    1

    3

    e1 e3

    e2

    Figure 19.10. Pictorial representations of graphs

    A graph consists of vertices joined by edges. A mathematical definition of a graph musttherefore rely on V, the set of vertices, and E, the set of edges. Each edge is associatedwith two vertices that is, there is a mapping from an edge to the ordered or unordered

    pair of vertices. This is summarized in the following definition:

    Definition 19.1: A graphG = (V , E , f ) consists of a nonempty set V, the set ofvertices(nodes, points) of the graph, a set E, the set ofedgesof the graph, and a mapping ffrom the set of edges Eto a set of ordered or unordered pairs of elements ofV . If anedge is mapped to an ordered pair, it is called a directed edge; otherwise, it is calledanundirected edge.

    Notice that the definition of a graph implies that with every edge of the graph G, wecan associate an ordered or unordered pair of vertices of the graph. If an edge e E isassociated with an ordered pair (u, v) or unordered pair {u, v}, whereu, v V, then we saythat the edge e joins the vertices u and v . Any two vertices joined by an edge in a graphare called adjacentvertices. We shall assume throughout the discussion that both the sets

    V and Eare finite. Usually, it will be convenient to write a graph G as (V, E), or simplyasG. In the former case, each edge is directly represented as the pair that it is mapped to,which eliminates the need to specify f.

    A graph in which every edge is directed is called a directed graph, or digraph. A graphin which every edge is undirected is called an undirected graph. If some edges are directedand some are undirected in a graph, the graph is called mixed.

    In the diagrams, a directed edge (arc) is shown as a line with an arrowhead that showsthe direction. The graphs given in Figure 19.10a and Figure 19.10c are directed graphs.The one given in Figure 19.10b is undirected. Notice that the edges e1, e2, and e3 inFigure 19.10a are associated with the ordered pairs (1, 2), (2, 3), and (3, 1), respectively.The set representation of the graph in Figure 19.10a is

    ({1, 2, 3}, {(1, 2), (2, 3), (3, 1)}).

    The edges e1, e2, and e3 in Figure 19.10b are associated with the unordered pairs {1, 2},{2, 3}, and{3, 1}, respectively. In Figure 19.10b, vertex 1 is adjacent to vertices 2 and 3.

    LetG = (V, E) be a graph and let e Ebe a directed edge associated with the orderedpair of nodes (u, v). The edge e is then said to initiate or originate at the node u and

  • 8/12/2019 Tremblay Chap 19

    13/106

    852 Graphs

    v1

    v3

    v2

    (b) Directed multigraph

    1

    4 3

    2

    (a) Undirected multigraphwith loops

    1

    3

    2

    (c) Directed graph with a loop

    Figure 19.11. Multigraphs and loops

    terminateor endat the node v . The nodes u andv are also called the initialand terminalnodes of the edge e. An edge e E, which joins the nodes u and v , whether it be directedor undirected, is said to be incidentto the nodes u and v .

    An edge of a graph that joins a node to itself is called a self-loop or sling, not to beconfused with a loop in a program. The direction of a loop is of no significance. Hence,

    it can be considered either a directed or undirected edge. Some authors do not allow anyloops in the definition of a graph.

    The graphs given in Figure 19.10 have no more than one edge between any pair ofnodes. In the case of directed edges, the two possible edges between a pair of nodes thatare opposite in direction are considered distinct. In some graphs, directed or undirected, wemay have certain pairs of nodes joined by more than one edge, as shown in Figure 19.11aand Figure 19.11b. Such edges are calledparallel. Note that there are no parallel edgesin the graph of Figure 19.11c. In Figure 19.11a, there are two parallel edges joining nodes1 and 2, two parallel edges joining nodes 2 and 3, and two parallel loops at node 2. InFigure 19.11b, there are two parallel edges associated with the ordered pair ( v1, v2).

    Any graph that contains some parallel edges is called a multigraph. In this case, themapping between edge and node pairs is not one-to-one. The shorthand notationG= (V, E)is not sufficient for representing a multigraph, and the full notation G = (V , E , f ) is needed.However, if there is no more than one edge between a pair of nodes (no more than one edgewith a specific direction in the case of a directed graph), such a graph is called a simplegraph. In this chapter, we deal primarily with simple graphs. The example graphs given inSection 19.1 are all simple graphs.

    We may have graphs in which numeric labels, called weights, are placed on the edges.For example, a graph representing a system of pipelines might have a weight associated witheach edge (pipe), which indicates the amount of some commodity that can be transferredthrough the pipe. Similarly, a graph of city streets may be assigned weights according tothe traffic density on each street. A graph in which weights are assigned to every edge iscalled a weighted graph.

    In a graph, a node that is not adjacent to any other node is called an isolated node. Agraph containing only isolated nodes is called a null graph. In other words, the set of edges

    in a null graph is empty.

    Definition 19.2: In a directed graph, for any node v , the number of edges that havev astheir initial node is called the outdegreeof node v . The number of edges that havevas their terminal node is called the indegreeofv, and the sum of the outdegree and

  • 8/12/2019 Tremblay Chap 19

    14/106

    Sec. 19.2. Basic Definitions of Graph Theory 853

    (a) (b)

    Figure 19.12. A graph and one of its subgraphs

    the indegree of a node v is called its total degree. In the case of an undirected graph,the total degree or just the degreeof node v is equal to the number of edges incidentwithv .

    The total degree of an isolated node is 0 and that of a node with a loop and no otheredges incident to it is 2.

    A simple result involving the notion of the degree of nodes of a graph is that the sumof the degrees (or total degrees in the case of a directed graph) of all the nodes of a graphmust be an even number that is equal to twice the number of edges in the graph.

    Some graph applications are concerned with only parts of a graph. The notion of asubset of a set is useful in formalizing what we mean by a part of a graph.

    Definition 19.3: Let Ube the set of nodes of a graph H and Vbe the set of nodes of agraph G such that U V . If, in addition, every edge ofHis also an edge ofG, thegraphH is called a subgraphof the graph G, which is expressed as HG.

    Naturally, the graph G and the null graph obtained from G by deleting all the edgesofG are also subgraphs ofG. Other subgraphs ofG can be obtained by deleting certainnodes and edges ofG. In Figure 19.12, the graph in part (b) is a subgraph of the graph inpart (a).

    LetG = (V, E) be a graph and XV. A subgraph whose nodes are given by the set Xand whose edges consist of all those edges ofG that have their initial and terminal nodes inX is called the subgraph induced byX. Thus, the subgraph in part (b) of Figure 19.12 is

    not an induced subgraph, but if the edge from the upper left node to the lower right nodeis included, the subgraph would be an induced subgraph of the graph in part (a).

    There are several special classes of simple graphs that frequently arise. We now brieflydescribe a few of these.

    A graph (V, E) is said to be complete if every node is adjacent to all other nodes in thegraph. A complete graph ofn nodes is denoted by Kn. Figure 19.13 shows the first fivecomplete graphs.

    Another type of simple graph is a bipartite graph. A simple graph G = (V, E) is calleda bipartite graphifVcan be partitioned into subsets V1 andV2 such that no two nodes ofV1 are adjacent and no two nodes ofV2 are adjacent. Consequently, an edge cannot jointwo nodes inV1 or two nodes in V2. The graph in Figure 19.14a is a bipartite graph, sincethe two disjoint subsets of nodes are V1 ={v1, v2} and V2 = {v3, v4, v5}, and all the edgesonly join nodes in V

    1to nodes in V

    2. However, Figure 19.14b is not a bipartite graph, since

    the nodes cannot be partitioned into two nonempty disjoint subsets where edges only joina node from one subset to a node in the other subset.

    Note that the theory of binary relations is closely linked to the theory of simple digraphs.Let G = (V, E) be a simple digraph. Every edge ofEcan be expressed by means of an

  • 8/12/2019 Tremblay Chap 19

    15/106

    854 Graphs

    K5K4K3K2K1

    Figure 19.13. Examples of complete graphs

    v3v2

    v1

    (a) (b)

    v2

    v1

    v5

    v3

    v4

    Figure 19.14. Bipartite and nonbipartite graphs

    ordered pair of elements ofV that is,E V V. However, any subset ofV V definesa relation in V. Accordingly, Eis a binary relation in Vwhose graph is the same as thesimple digraphG.

    Problems 19.2

    1. Show that the sum of indegrees of all the nodes of a simple digraph is equal to the sum of theoutdegrees of all its nodes and that this sum is equal to the number of edges of the graph.

    2. Because graphs can be drawn in an arbitrary manner, it can happen that two diagrams which

    look entirely different from one another may represent the same graph. See, for example,parts (a) and (a) of Figure 19.15. Two graphs areisomorphic if there exists a one-to-onecorrespondence between the nodes of the two graphs that preserves adjacency of the nodes,as well as the directions of the edges, if any.

    According to the definition of isomorphism, we note that any two nodes in one graph whichare joined by an edge must have the corresponding nodes in the other graph also joinedby an edge, and, hence, a one-to-one correspondence exists between the edges as well. Thegraphs given in parts (a) and (a) of Figure 19.15 are isomorphic because of the existence ofa mapping

    1 u1, 2 u3, 3 u4, and 4 u2

    Under this mapping, the edges (1, 3), (1, 2), (2, 4), and (3, 4) are mapped into (u1, u4), (u1, u3),(u3, u2), and (u4, u2), which are the only edges of the graph in Figure 19.15a. Show that thedigraphs given in parts (b) and (b) of Figure 19.15 are isomorphic.

    3. Draw all p ossible simple digraphs having four nodes. Show that there is only one digraphwith no edges, one with one edge, two with two edges, three with three edges, two with fouredges, one with five edges, and one with six edges. Assume that there are no loops and thatisomorphic graphs are not distinguishable.

    4. Show that the graphs given in Figure 19.16a and Figure 19.16b are isomorphic.

  • 8/12/2019 Tremblay Chap 19

    16/106

  • 8/12/2019 Tremblay Chap 19

    17/106

    856 Graphs

    v1 v2

    v4 v3

    v6 v7

    v5v8

    u1 u2

    u4 u3

    u6 u7

    u5 u8

    Figure 19.17. Nonisomorphic graphs

    ADT VertexUosVertexUos( id) // constructor for a vertex

    index() // index of the vertexString toString() // string representation of the vertex

    Figure 19.18. VertexUosADT

    The first thing to note is that every graph involves vertices or nodes and edges. These

    are parts of a graph, but distinct from it, so they should have their own ADT. A vertexis an abstract entity that we draw as a small circle. To distinguish one from another, it isconvenient for them to have distinct labels. Thus, each vertex will be given a unique index.

    The public constructor for a vertex has its index as a parameter. As theindexis used toguarantee vertex uniqueness, there is no operation to change the indexof a vertex. Finally,a String representation of the vertex (giving its index) is available via the toString()method. Thus, the features of the VertexUosADT are those listed in Figure 19.18.

    An edge is identified by the two vertices at its ends. Rather than using the graph theorynotation of initial and terminal vertices, they will be called firstItem and secondItem.This is in keeping with the approach of using the same names for the same concepts even indifferent contexts. Normally, the ends of one edge are distinct from the ends of every otheredge, so the ends of an edge are sufficient to distinguish it from another edge. Formally,there are two types of edges: directed and undirected. Rather than having two ADTs, adirected edge (u, v) will be represented by an instance of EdgeUos with u = firstItemand v = secondItem. An undirected edge{u,v}will be represented by two directed edges:(u, v) and (v, u).

    The public constructor for an edge has two vertices as parameters. No methods areprovided to change the ends of an edge. Other features for the EdgeUos ADT are themethodtoString() to return theStringrepresentation of the edge, a method to determinewhether a given vertex is an end of the current edge, and a method that given one end ofan edge will return the vertex at the other end. Thus, for theEdgeUosADT, we have thefeatures given in Figure 19.19.

    Now, consider theGraphUos ADT. A graph is a container of vertices and edges. Hence, itmakes sense to have a constructor to create an empty graph with no vertices or no edges and

    then methods to add vertices and edges. In addition, we will take the approach that verticesand edges only exist in a graph. As a result, instead of having a method to add a vertex, themethod will create a vertex to match the specification provided by the parameters and store

  • 8/12/2019 Tremblay Chap 19

    18/106

    Sec. 19.3. Graph ADT 857

    ADT EdgeUosEdgeUos(VertexUos v1, VertexUos v2) // constructor for an edgeVertexUos firstItem() // initial vertex of the edgeVertexUos secondItem() // terminal vertex of the edge has(VertexUos v) // does the edge have vertex v as an end?VertexUos other(VertexUos v) // vertex other than v that is an end of the edgeString toString() // string representation of the edge

    Figure 19.19. EdgeUosADT

    the vertex in the graph. Edges are handled in a similar way. The vertices of a graph arestored in an array so that an individual vertex is accessed by index. As a result, a capacity,which specifies an upper limit on the number of vertices in the graph, will be associated withthe graph. This capacity will be specified when the graph is created. Normally, a graph haseither all directed edges, and is called a directed graph, or all undirected edges, and is calledanundirected graph. Whether a graph is to be directed or undirected will be specified whenit is created. These key features of the GraphUosADT are given in part 1 of Figure 19.20.These include the container features, insertion procedures, and size measurement features.An additional key feature is the functionadjacent(), which tests whether two vertices are

    adjacent (i.e., whether there is an edge between them).Whereas the ADT features of part 1 are sufficient for most applications, it is convenientto have a number of additional features. First, graphs can be very large. Thus, it can beclumsy and error prone to build a graph vertex by vertex and edge by edge. Therefore, thereare two methods to read in a graph: read() for the interactive entry of a graph from theterminal, and fileRead() for the entry of a graph from a text file. The format of a graphas read by fileRead() is the same as that produced by toString(). Hence, it is easy tosave a graph to a file for later retrieval. Also, it is convenient to have search methods, anda current vertex and a current edge that are set by the search methods. These additionalfeatures of the GraphUosADT are in part 2 of Figure 19.20.

    Finally, it is useful to iterate through all vertices and through all edges incident to a spec-ified vertex. Therefore, the features of part 3 of Figure 19.20 are also included. The proce-duresgoFirst()and goForth()iterate through the vertices of the graph. When doing so,

    they set the instance variables accessible by itemExists(),item(), and itemIndex(). It-eration through the edges incident to a vertex is performed by eGoFirst()andeGoForth(),which modify the result obtained from the functions iterationIndex()(the index of thevertex being iterated), eItemExists(), eItem(), adjItem() (the adjacent vertex discov-ered in the iteration), and adjIndex()(the index of the adjacent vertex). Note that vertexand edge iteration are independent of each other. One does not affect the other, and theedge list being iterated is not necessarily the edge list of the current vertex. However, onlyone vertex iteration can be done at a time, since starting a second iteration will destroythe state (the internal storage of the present position in the iteration) of the first iteration.For the same reason, only one edge iteration can be done at a time. A position in a graphrecords its current vertex, its current edge, and the status of the two iterators. Methods areprovided to store the current position and move to a stored position.

    As an example of using the GraphUos constructors and members, Figure 19.21a has

    a sequence of operations to build and print a graph. For simplicity of presentation, theADT for a graph was not defined to use generic types. However, the actual implementationthat we will use will have two generic parameters. Figure 19.21a shows the specification ofthe generic parameters for the graph. The graph that is built is shown in Figure 19.21b,

  • 8/12/2019 Tremblay Chap 19

    19/106

    858 Graphs

    ADT GraphUos(part 1)GraphUos(

    cap) // make an empty undirected graph with vertex capacity capGraphUos(

    cap, String graphChoice) /* Make an empty graph with vertex capacity cap,and either directed or undirected as specified by graphChoice. */

    vNewIth(

    index) // insert a vertex with the specified index

    eNew(VertexUos v1, VertexUos v2) // insert an edge with ends v1 and v2 eNew( i, j) // insert an edge whose ends have indices i and j

    capacity() // the vertex capacity of the graph n() // current number of vertices

    m() // current number of edges

    directed() // is the graph directed?

    adjacent(VertexUos v1, VertexUos v2) // is there an edge from v1 to v2?

    isEmpty() // is the graph empty (no vertices)? isFull() // is the graph full (n = capacity)?

    wipeOut() // remove all vertices (and edges)String toString() // string representation of the graph

    (part 2) read() // read in a graph from the terminal

    fileRead(File infile) // read in a graph from infile

    goTo(VertexUos v) // move the vertex cursor to vertex v goIth( index) // move the vertex cursor to the vertex with index index

    itemExists() // is there a current vertex as specified by the vertex cursor?VertexUos item() // the current item (vertex)

    itemIndex // index of the current vertex

    eSearch(VertexUos v1, VertexUos v2) // move the edge cursor to the edge (v1, v2)

    eItemExists() // is there a current edge as specified by the edge cursor?EdgeUos eItem() // the current edge

    (part 3)

    goFirst() // go to the first vertex

    goForth() // go to the next vertex

    after() // moved past the last vertex?

    eGoFirst(VertexUos v) // go to the first edge of v to start an edge list iteration

    eGoForth() // go to the next edge of the edge list eAfter() // moved past the end of the edge list?

    iterationIndex() // index of the vertex being edge iteratedVertexUos adjItem() // vertex of eItem other than the one whose edge list is being iterated

    adjIndex() // the index of adjItemGraphPositionUos currentPosition() // the current position in the graph

    goPosition(GraphPositionUos pos) // go to the specified position in the graph

    Figure 19.20. GraphUosADT

    along with the result of the toString() operation in Figure 19.21c. The first line in thetoString()output gives the number of vertices in the graph (i.e., 4) and whether the graphis directed ot undirected. Each subsequent line gives the index of a vertex and its associatedlist of adjacent vertices. Each adjacent vertex is specified by its index. A zero denotes theend of a list. The output is terse so that a graph can be written to a file using toString()and read later using the fileRead()procedure.

    As another example of using these operations, consider the construction of a specialmatrix called the adjacency matrix, A, of a graph. The adjacency matrix is defined asfollows:

  • 8/12/2019 Tremblay Chap 19

    20/106

    Sec. 19.3. Graph ADT 859

    1

    2

    3

    4

    (b)

    4 directed1 : 2 3 4 02 : 03 : 1 04 : 0

    (c)

    a =

    0 1 1 10 0 0 01 0 0 00 0 0 0

    ( ((d)

    GraphLinkedRepUos g = newGraphLinkedRepUos

  • 8/12/2019 Tremblay Chap 19

    21/106

    860 Graphs

    [ ][ ] computeAdjacencyMatrix(GraphUos g){

    [ ] [ ] a =

    [g.capacity()][g.capacity()];g.goFirst(); (!g.after()){

    g.eGoFirst(g.item());

    (!g.eAfter()){

    matrixSetItem(a, 1, g.iterationIndex(), g.adjIndex());g.eGoForth();

    }g.goForth();

    } a;

    }

    /** Set the item with indices i and j.Analysis: Time = O(1) */

    matrixSetItem( [ ][ ] a, x, i, j){

    /* Indices 1 through n are mapped to 0 through n - 1. */a[i-1][j-1] = x;

    }

    /** The item with indices i and j.Analysis: Time = O(1) */

    matrixItem( [ ][ ] a, i, j){

    /* Indices 1 through n are mapped to 0 through n - 1. */

    a[i-1][j-1];}

    Figure 19.22. Code to compute the adjacency matrix of a graph

    graph theory, while Java starts the indices of an array at 0. Methods like matrixSetItem()

    andmatrixItem()can be used to confine handling the mapping of 1 through nto 0 throughn - 1to two methods. The time to create and initialize the matrix is ( n2). For the nestedloops, the time depends on the efficiency of the iteration operations. For any reasonablerepresentation of the graph, the n vertices can be found in (n) time, and all the edgesincident to a given vertex can also be found in O(n) time. Thus, (n2) also bounds thetime for these loops and the whole algorithm.

    Problems 19.3

    1. Using the operations of the GraphUos ADT, give an algorithm to count the number of edgesin a graph. Do not assume that this value is stored in attribute m. Note: If the graph isundirected, be careful not to obtain a value that is twice as large as it should be.

    2. Using the operations of the GraphUos ADT, give an algorithm to determine the degree ofeach vertex.

    3. Using the operations of the GraphUos ADT, give a function to test whether the graph iscomplete.

  • 8/12/2019 Tremblay Chap 19

    22/106

    Sec. 19.4. Paths, Reachability, and Connectedness 861

    19.4 Paths, Reachability, and Connectedness

    In this section, we will introduce some additional terminology associated with a simpledirected graph (digraph). During the course of our discussion, we shall also indicate howthe same terminology and concepts can be extended to simple undirected graphs.

    In a graph, one of the key concepts is that of a path. Consider the digraph given in

    Figure 19.23. Some of the paths originating in node 1 and ending in node 12 areP1 = 1, 2, 3, 12

    P2 = 1, 2, 3, 4, 5, 6, 11, 3, 12

    P3 = 1, 2, 3, 4, 5, 7, 8, 10, 11, 3, 12

    P4 = 1, 2, 3, 4, 5, 7, 9, 10, 11, 3, 4, 5, 6, 11, 3, 12

    where. . .is used to represent a sequence. Although this specifies that a path is a sequenceof nodes, formally a path is a sequence of edges.

    Definition 19.5: LetG = (V, E) be a simple digraph. A sequence of edges is called a pathofG if and only if the terminal node of each edge in the path is the initial node of thenext edge, if any, in the path.

    Thus, a path has the form

    (vi1, vi2), (vi2, vi3), . . . , (vik2, vik1), (vik1, vik),

    where it is assumed that all the nodes and edges appearing in the path are in V and E,respectively. As we have seen, it is customary to write such a path as the sequence

    vi1, vi2, . . . , vik1, vik.

    Note that not all edges or nodes appearing in a path need be distinct. Also, for a givengraph, any arbitrary set of nodes written in any order does not necessarily give a path. Infact, each node appearing in the path must be adjacent to the nodes appearing just beforeand after it, except in the case of the first and last nodes. We now elaborate on this notion.

    A path is said to traversethrough the nodes appearing in the sequence, originatingatthe initial node of the first edge and endingat the terminal node of the last edge in thesequence.

    Definition 19.6: The number of edges appearing in the sequence of a path is called thelengthof the path.

    Note that this definition differs from the definition of the length of a path in a tree. In atree, the length of a path is the number of nodes traversed by the path. The tree definitionis used to reflect the number of tests that must be done to find a value in an ordered binarytree. For a graph, a path represents a route from one node to another node by means ofdirect links (edges). The normal measure of the length of a route is the sum of the lengthsof the direct links. Hence, for a graph with no distances associated with its edges, the length

    of a path is the number of edges.

    Definition 19.7: A path in a digraph is called a simple path if all the edges are distinct.A path in which all the nodes are distinct is called an elementary path. As a specialcase, a path is still calledelementaryif the originating and ending nodes are the same.

  • 8/12/2019 Tremblay Chap 19

    23/106

    862 Graphs

    12

    while (!finished)

    end of loop statement

    end of procedure

    T

    s3

    s4, s6 s7

    s8

    3

    4

    7

    10

    8 96

    11

    F

    T

    TF

    2

    F

    s2

    1 s1

    5

    s9

    flag1 == 0

    flag2 == 0

    (a) (b)

    voidwhatever(){

    s1s2while (!finished){

    s3if (flag1 == 0){

    s4s5

    }else

    {if (flag2 == 0)

    s6else

    s7s8

    }}s9

    }

    s5

    Figure 19.23. Modeling a module with a flow graph

    According to the definition, a path is called simpleif no edge is repeated (edge simple),and a path is called elementary if no node is repeated (node simple), except that the firstand last nodes can be the same. Obviously, every elementary path of a digraph is alsosimple. The previous paths P1, P2, and P3 of the digraph in Figure 19.23 are all simple,but the paths P2 andP3 are not elementary, and P4 is not even simple.

    Definition 19.8: A path that originates and ends in the same node is called a cycle (cir-cuit). A cycle is called simple if no edge in the cycle appears more than once in thepath (i.e., the path is simple). A cycle is called elementary if the path is elementary.

    For an elementary cycle, the initial node appears twice (at the start and at the end),and the other nodes appear exactly once. The following are some of the cycles in the graphof Figure 19.23:

    C1 = 3, 4, 5, 6, 11, 3

    C2 = 3, 4, 5, 7, 8, 10, 11, 3

    C3 = 3, 4, 5, 6, 11, 3, 4, 5, 6, 11, 3

  • 8/12/2019 Tremblay Chap 19

    24/106

    Sec. 19.4. Paths, Reachability, and Connectedness 863

    Figure 19.24. Examples of acyclic graphs

    Observe that any path which is not elementary contains cycles traversing through thosenodes that appear more than once in the path. By deleting such cycles, one can obtain an ele-mentary path. For example, in the pathC3, if we delete the cycle (3, 4), (4, 5), (5, 6), (6, 11),(11, 3), we obtain the path C1, which also originates at 3, ends in 3, and is an elementarypath. Some authors use the term path to mean only the elementary paths, and theylikewise apply the notion of the length of a path only to elementary paths.

    The digraphs (directed graphs) generated by many applications never contain cycles.For instance, scheduling graphs never contain cycles. This type of graph has led to the

    following definition:

    Definition 19.9: A simple digraph that does not have any cycles is called acyclic.

    Naturally, acyclic graphs cannot have any self-loops. Examples of acyclic graphs are givenin Figure 19.24.

    If there is a path from vertex u to vertex v , v is said to be reachablefrom u. Note thatthe concept of reachability is independent of the number of alternate paths from u to v andalso of the lengths of the paths. For the graph of Figure 19.23, we have paths P1 and P3from node 1 to node 12. Any one of these paths is sufficient to establish the reachability ofnode 12 from node 1.

    If a nodev is reachable from the nodeu, a path of minimum length from u to v is calledashortest path, orminimum-length path. The length of a shortest path from nodeu to node

    v is called the distance between them and is denoted by d(u, v). Some properties of thedistance function are

    d(u, v) 0

    d(u, u) = 0

    d(u, v) + d(v, w) d(u, w)

    The second equality follows from assuming that a trivial zero-length path exists from everynode to itself. The last inequality is called thetriangle inequality. Ifv is not reachable fromu, then it is customary to write d(u, v) = . Note also that ifv is reachable from u, itdoes not imply that u is reachable from v . Moreover, even if each one can reach the other,d(u, v) is not necessarily equal to d(v, u). Finally, in a simple digraph, the length of anyelementary path is less than or equal to n 1, wheren is the number of nodes in the graph.

    This follows, since there are only n distinct nodes and every node in an elementary pathmust be distinct.

    Let us now briefly see how the concepts of path and cycle can be extended to undirectedgraphs:

  • 8/12/2019 Tremblay Chap 19

    25/106

    864 Graphs

    1 2

    7 8

    3 4 5 6

    9 10

    11

    Figure 19.25. Example of a disconnected graph

    Definition 19.10: In a simple undirected graph, a sequencev1, v2, . . . , vdforms apathiffori = 2, 3, . . . , d there is an undirected edge{vi1, vi}. The edge{vi1, vi}is said tobe on the path. The length of the path is given by the number of edges on the path,which in this case is d 1. Ifv1 = vd, the path forms a cycle.

    Recall that the definition of a path for a directed graph requires that the edges appearingin the sequence must have specific initial and terminal nodes. The terminal node of an edgemust be the same as the initial node of the next edge. In the case of a simple undirected

    graph, an edge is given by an unordered pair, and any one of the nodes in the ordered paircan be considered as the initial or terminal node of the edge. To apply the definition of apath in a directed graph to an undirected graph, we can consider every edge in an undirectedgraph to be replaced by two directed edges in opposite directions. Once this replacementis done, the result is a directed graph, and the definitions of path, cycle, elementary path,simple path, and so on, are carried over to undirected graphs.

    Cycles in undirected graphs are slightly different from those in digraphs. For example,in an undirected graph, we do not consider the path v1, v2, v1a simple cycle when {v1, v2}is an edge. Traversing an undirected edge in one direction and also in the other direction isconsidered to have traversed the same edge twice. More generally, we do not consider thetraversal of a sequence of edges in a forward direction and then in the reverse direction asimple cycle. A simple cycle in an undirected graph is a simple path.

    We shall now introduce an important concept the connectedness of nodes in a graph.

    Definition 19.11: In an undirected graph, two nodes are said to be connected if the twonodes are reachable from one another (i.e., there is a path between them). Moreover,an undirected graph is said to be connected if every pair of nodes of the graph isconnected.

    Although most graphs are connected, including the ones seen so far in this chapter, not allgraphs are connected. For example, the graph in Figure 19.25 is not connected. It has fourparts, calledconnected components, each of which is connected and disjoint from the others.

    The notion of connectedness cannot be applied to directed graphs without some furthermodifications. This is because in a directed graph if a nodeu is reachable from anothernode v, the node v may not be reachable from u. As a result, there are three notionsof connectedness in directed graphs. Two nodes are called strongly connected if each

    is reachable from the other. For example, in Figure 19.23, nodes 6 and 8 are stronglyconnected. Two nodes are called unilaterally connected if one of the nodes can reach theother. In Figure 19.23, node 1 is unilaterally connected to node 12, but they are notstrongly connected. Note that two strongly connected nodes are automatically unilaterallyconnected, since each can reach the other. Finally, two nodes in a directed graph are called

  • 8/12/2019 Tremblay Chap 19

    26/106

    Sec. 19.5. Graph Representations 865

    v1

    v2

    v4

    v3

    Figure 19.26. A digraph for path analysis

    v2 v3

    v1 v4 v5

    Figure 19.27. A digraph for degree analysis

    weakly connectedif they would be connected in the undirected graph formed by convertingeach directed edge to an undirected edge. For all the digraphs given so far, every node isweakly connected to every other one in the digraph. These notions can be used to definestrongly connected components, unilaterally connected components, and weakly connectedcomponents in a directed graph. This will be pursued further in Section 19.8.1.

    Problems 19.4

    1. Give three different elementary paths from v1 to v3 for the digraph given in Figure 19.26.What is the shortest distance betweenv1 and v3? Is there a cycle in the graph?

    2. Find all the indegrees and outdegrees of the nodes of the graph given in Figure 19.27. Giveall the elementary cycles of this graph. Obtain an acyclic digraph by deleting one edge of the

    given digraph. List all the nodes that can reach every other node in the digraph.

    3. For the graph of Figure 19.25, determine all the elementary paths from node 1 to node 8.Also, determine all the elementary paths and all the simple paths from node 4 to node 10.

    4. For each node of the graph of Figure 19.25, determine the set of nodes connected to it.

    19.5 Graph Representations

    A graph consists of vertices, edges, and (possibly) labels or weights (or both) on the verticesand edges. For small graphs, a diagram can display this information in a convenient wayfor human use. However, graphs are usually so large that a diagram becomes an incom-prehensible maze, and also a nondiagramatic representation is needed for internal storage.Thus, this section will discuss two ways to internally represent a graph. It will also define

    the graph class GraphUosthat corresponds to the ADT of Section 19.3.We begin with the vertices of a graph. If the vertices only consist of the consecutive

    integers 1, 2, . . ., n, a vertex can be implicitly represented by a variable with a valuebetween 1 andn. For simple applications, this may be sufficient. However, in more complex

  • 8/12/2019 Tremblay Chap 19

    27/106

    866 Graphs

    applications, there is more to a vertex than an index. For example, often a vertex has anameas well as its index. When a vertex has more features than its index, an object shouldbe used to represent the vertex. The class for objects that represent vertices, shown inFigure 19.28, is a straightforward implementation of the VertexADT.

    In a graph, the vertices need to be stored in some container, unless they are implicitlyrepresented by an integer value. The container usually used is an array for the following

    three reasons:

    1. The number of vertices is often known or at least bounded.

    2. Each vertex usually has a unique indexthat can be used as an index into the array.

    3. Fast vertex access is achieved by accessing each vertex by itsindex.

    Hence, the following will be used:

    V[ ] vertexArray;

    where V is the generic type to represent the vertex type. Other containers could be usedto store the vertices. A linked list could be used, but it would not permit O(1) access to avertex, and the flexibility of linked lists in handling insertions and deletions is usually not

    needed. If vertices have names, then a linear search would be needed to find a vertex byitsname. Other data structures could be used with the namefield as a key; for example, anordered tree or a hash table. However, it is usually sufficient to have fast access of verticesbyindex.

    The other important part of a graph is its edges. An individual edge consists of a pair ofvertices as per the ADT. In some graph representations, no object is created to represent anedge, so no edge class exists. However, having an edge class provides additional flexibility,so we define one. Our edge class, EdgeUos, is defined in terms of class PairUos, as shownin Figure 19.29. Note that the class is defined to have one generic parameter to representthe vertex type. Normally, the vertex type will be VertexUos, but if additional fields ormethods are needed for a vertex, then a descendant of VertexUos should be defined, andthe edge should store the descendant type. Using a generic type for the vertex type of anedge makes it easy to use such a descendant vertex type. By having a class for an edge, a

    descendant of the edge class can be easily defined to give an edge a label or weight. Themethod toStringGraphIO() with a vertex parameter is used to output the index of theother end of an edge when printing the list of adjacent vertices of a given vertex.

    A graph can have many edges that need to be stored in one container, say, an array ora linked list. However, the best storage representation is one that facilitates the common orfrequent operations. For a graph, the common operations are testing for the presence of aspecific edge, the function adjacent(v1, v2)of the ADT, and finding the edges incident toa specific vertex. If all the edges were stored in one array or one linked list, the whole datastructure (or at least much of it) would need to be searched to do either of these commonoperations. Withm edges, it would mean that the operations could require time O(m). Fora graph with n vertices, there can be as many as n (n 1) edges, one for each possibleordered pair. This would mean that these common operations might require time O(n2),which is often unacceptable for large graphs.

    Depending on which of the common graph operations is used the most, there are twocommon representations for the storage of the edges of a graph. In the Uos data struc-ture library, there is a class for each representation and a common abstract ancestor class,GraphUos, with the specification of the common aspects. Part of the class GraphUos is

  • 8/12/2019 Tremblay Chap 19

    28/106

    Sec. 19.5. Graph Representations 867

    dslib.graph;

    /** A vertex of a graph where the vertex has a unique index. */

    VertexUos

    Cloneable{

    /** The index of this vertex. */ index;

    /** Construct a new vertex with id as its index.
    Analysis: Time = O(1)@param id index of the new vertex */

    VertexUos( id){

    index = id;}

    /** The index of this vertex.
    Analysis: Time = O(1) */

    index(){

    index;}

    /** String representation of the vertex.
    Analysis: Time = O(1) */

    String toString(){

    String.valueOf(index);}

    /** A shallow clone of this vertex.
    Analysis: Time = O(1) */

    VertexUos clone()

    {

    {

    (VertexUos)

    .clone();} (CloneNotSupportedException e){

    /* Should not occur: implements Cloneable. */e.printStackTrace();

    ;}

    }}

    Figure 19.28. The VertexUosclass

  • 8/12/2019 Tremblay Chap 19

    29/106

    868 Graphs

    dslib.graph;

    dslib.base.PairUos; dslib.exception.ItemNotFoundUosException;

    /** An edge of a graph that has firstItem and secondItem as its ends. Method has

    tests whether a vertex is an end of the edge, and method other returns the other end. */ EdgeUos PairUos{

    /** Construct a new Edge object.Anaysis: Time = O(1)@param v1 initial vertex of the new edge@param v2 terminal vertex of the new edge */

    EdgeUos(V v1, V v2){

    (v1, v2);}

    /** Determine if v is an item of the edge.Analysis: Time = O(1)@param v vertex to determin whether it belongs to the edge */

    has(V v)

    {

    ((v == firstItem) || (v == secondItem));}

    /** The other item of the edge.Analysis: Time = O(1)PRECONDITION:

    has(v)@param v vertex adjacent vertex to v via this edge */

    V other(V v) ItemNotFoundUosException{

    (!has(v))

    ItemNotFoundUosException("Cannot return the other item "+ "since this vertex does not exist.");

    (firstItem == v)

    secondItem;

    // must have (secondItem == v) firstItem;

    }

    /** String representation of the edge for output of vs adjacency list in a graph.Analysis: Time = O(1) */

    String toStringGraphIO(V v){

    Integer.toString(other(v).index());}

    /** A shallow clone of this edge.Analysis: Time = O(1) */

    EdgeUos clone(){

    (EdgeUos) .clone();

    }}

    Figure 19.29. The EdgeUosclass (part 2)

  • 8/12/2019 Tremblay Chap 19

    30/106

    Sec. 19.5. Graph Representations 869

    shown in Figure 19.30. The next paragraphs will discuss some of the aspects of this class.Note that only part of the class is shown, as it is a large class, and many of its methods areeither abstract or straightforward to implement. In particular, no storage is specified foredges, and very few of the edge operations are implemented.

    The first thing to note about the class GraphUos is that it is generic with a parameterfor the vertex type and a parameter for the edge type. Normally, these two types will be

    VertexUosand EdgeUos. However, since it is often useful to use descendants of them, theclass is defined to use generic types. The fieldsvertexTypeand edgeTypewill be explainedshortly, but for now it is sufficient to know that they store the Stringnames for the vertextype and edge type. The class GraphUos has 12 constructors, although only six of themare shown in the figure. There are only four basic objectives of the constructors. Fourconstructors are used to create an empty graph. This graph will have an upper limit onits number of vertices, to be called its capacity. The empty graph has no vertices and noedges. Two constructors are used to read graph from a text file. It is assumed that theinput for the graph has the same format as is produced by the toString method. Thisformat is shown in Figure 19.21c. The next two constructors are used to read a graph fromthe console. The user is prompted to enter the graph information. The edges are enteredfor one vertex at a time. The last four constructors are used to create a random graph.They will be discussed shortly.

    The first two constructors shown in the figure for the class GraphUos are used to con-struct empty graph with a specific capacity. The first constructor is shorthand for thesecond one. The second one shows the creation of the vertex array, and the choice be-ing made whether the graph is to be directed or undirected. It also invokes the methodcreateEdgeDataStructurethat creates the data structure to hold the edges. This methodis abstract in class GraphUos, as this class does not deal with how to store the edges. Theconstructor parametersvertexTypeVand edgeTypeEare assigned to the fields vertexTypeandfieldTypethat are used for vertex and edge construction. These fields store that fullyqualified names of the vertex class and the edge class. The first constructor simply invokesthe second constructor with the two parameters for the default types.

    The next two constructors of the figure are used to read a graph from a text file. Againthe first of these assumes the vertex and edge types are the default ones, while for thesecond constructor the user can specify other types for the vertices and edges. All the workof reading the graph is placed in the method fileRead. If the user needs to modify the fileformat, for example to supply additional information, then this method can be overridden.The following two constructor are for reading the graph from the console. Again, the defaulttypes are used for vertices and edges with the first of these constructors, while the secondgives the user the chance to specify other types. Again, the bulk of the work in put in amethod that is called read.

    The last two constructors of the figure are for the generation of a random graph. Oneparameter specifies the number of vertices for the graph, while another specifies the averagedegree of a vertex. The second constructor shows the code for creating a random graph. Themethod uses the average degree to compute the probability of an individual edge, called thedensity. Given the density, each edge is generated with this probability. The method takescare to not generate any self-loops, (i, i) edges, and each undirected edge is only considered

    wheni < j.Following the constructors, the figure shows the methods to create a vertex and to createan edge. The method createNewVertex shows the use of the vertexType field. First,note that an instance of a generic type cannot be directed created since its actual type isunknown. However, the class GraphUos was defined with a generic type for the vertices,

  • 8/12/2019 Tremblay Chap 19

    31/106

    870 Graphs

    dslib.graph;

    dslib.base.*; dslib.exception.*;

    java.io.*; java.util.Random; java.util.Scanner;

    /** A graph class that is the base of matrix and linked graph representations. The constructorsprovide the user with a choice of directed or undirected graph structures. In addition,a graph can be constructed empty (no vertices or edges), read from the console,read from a text file, or randomly generated. This class has all the capabilitiesof a LinearIterator (goBefore, goFirst, goForth, and goAfter) so the vertices of the graphcan be iterated in a linear manner. This class defines various abstract methods for traversingedges of the current vertex (eGoFirst, eGoForth, and eSearch), which are implementedin matrix and linked graph representations. Classes that extend this class need to overridethe createNewEdge or createNewVertex methods, if they use specialized edges or vertices. */

    GraphUos

    ContainerUos, LinearIteratorUos, CursorSavingUos{

    /** Array that stores each vertex in the position corresponding to its index. */ V[ ] vertexArray;

    /** Is the graph directed? Defaults to undirected. */

    directed = false;

    /** Is the graph directed?.
    Analysis: Time = O(1) */

    directed(){

    directed;}

    /** The actual type of the vertices (extends VertexUos). */ String vertexType;

    /** The actual type of the edges (extends EdgeUos). */ String edgeType;

    /** Construct a new graph with capacity for up to cap vertices,with vertex type dslib.graph.VertexUos and edge type dslib.graph.EdgeUos,and make it directed or undirected according to graphChoice.
    Analysis: Time = O(cap)
    PRECONDITION:

    ((graphChoice.charAt(0) == u) || (graphChoice.charAt(0) == U))|| (( graphChoice.charAt(0) == d) || (graphChoice.charAt(0) == D))

    @param cap Maximum number of vertices allowed in the graph@param graphChoice Indicates whether the graph is directed or indirected */

    GraphUos(

    cap, String graphChoice)

    InvalidArgumentUosException{

    ("dslib.graph.VertexUos", "dslib.graph.EdgeUos", cap, graphChoice);}

    Figure 19.30. Part of the GraphUosclass (part 1)

  • 8/12/2019 Tremblay Chap 19

    32/106

    Sec. 19.5. Graph Representations 871

    /** Construct a new graph with capacity for up to cap vertices,with vertex type vertexTypeV and edge type edgeTypeE,and make it directed or undirected according to graphChoice.
    Analysis: Time = O(cap)
    PRECONDITION:

    ((graphChoice.charAt(0) == u) || (graphChoice.charAt(0) == U))|| (( graphChoice.charAt(0) == d)|| (graphChoice.charAt(0) == D))

    @param vertexTypeV The name of the type for the vertices of the graph@param edgeTypeE The name of the type for the edges of the graph@param cap Maximum number of vertices allowed in the graph@param graphChoice Indicates whether the graph is directed or indirected */

    @SuppressWarnings("unchecked") GraphUos(String vertexTypeV, String edgeTypeE, cap, String graphChoice)

    InvalidArgumentUosException{

    vertexType = vertexTypeV;edgeType = edgeTypeE;vertexArray = (V[ ]) VertexUos[cap];

    ((graphChoice.charAt(0) == u) || (graphChoice.charAt(0) == U))

    directed = false; ((graphChoice.charAt(0) == d) || (graphChoice.charAt(0) == d))

    directed = true;

    InvalidArgumentUosException("Invalid argument--graphChoice "+ "must be directed or undirected only");

    createEdgeDataStructure();}

    /** Constructor the data structure to hold the edges of the graph. */ createEdgeDataStructure();

    /** Construct a new graph with the graph read from a text file,vertex type dslib.graph.VertexUos, and edge type dslib.graph.EdgeUos.
    Analysis: Time = O(size of the file)@param fileName The name of the text file that contains the graph */

    GraphUos(String fileName)

    RuntimeException{

    ("dslib.graph.VertexUos", "dslib.graph.EdgeUos", fileName);}

    /** Construct a new graph with the graph read from a text file,vertex type vertexTypeV and edge type edgeTypeE.

    Analysis: Time = O(size of the file)
    @param vertexTypeV The name of the type for the vertices of the graph@param edgeTypeE The name of the type for the edges of the graph@param fileName The name of the text file that contains the graph */

    GraphUos(String vertexTypeV, String edgeTypeE, String fileName){

    vertexType = vertexTypeV;edgeType = edgeTypeE;fileRead(fileName);

    }

    Figure 19.30. Part of the GraphUosclass (part 2)

  • 8/12/2019 Tremblay Chap 19

    33/106

    872 Graphs

    /** Construct a new graph with the graph read from the console,vertex type dslib.graph.VertexUos, and edge type dslib.graph.EdgeUos.
    Analysis: Time = O(size of the input) */

    GraphUos(){

    ("dslib.graph.VertexUos", "dslib.graph.EdgeUos");}

    /** Construct a new graph with the graph read from the console,vertex type vertexTypeV and edge type edgeTypeE.

    Analysis: Time = O(size of the input)
    @param vertexTypeV The name of the type for the vertices of the graph@param edgeTypeE The name of the type for the edges of the graph */

    GraphUos(String vertexTypeV, String edgeTypeE){

    vertexType = vertexTypeV;edgeType = edgeTypeE;read();

    }

    /** Construct a new random graph with numVertices vertices, with vertextype dslib.graph.VertexUos and edge type dslib.graph.EdgeUos,directed or undirected according to graphChoice, and the edgesrandomly generated so as to yield an average degree of aveDegree.
    Analysis: Time = O(numVertices*aveDegree)PRECONDITION:

    ((graphChoice.charAt(0) == u) || (graphChoice.charAt(0) == U))|| (( graphChoice.charAt(0) == d) || (graphChoice.charAt(0) == D))

    @param numVertices The number of vertices for the graph@param aveDegree The desired average degree of the vertices@param graphChoice Indicates whether the graph is directed or indirected */

    GraphUos( numVertices, aveDegree, String graphChoice) InvalidArgumentUosException

    {

    ("dslib.graph.VertexUos", "dslib.graph.EdgeUos", numVertices,aveDegree, graphChoice);

    }

    Figure 19.30. Part of the GraphUosclass (part 3)

  • 8/12/2019 Tremblay Chap 19

    34/106

    Sec. 19.5. Graph Representations 873

    /** Construct a new random graph with numVertices vertices, with vertextype vertexTypeV and edge type edgeTypeE, make it directed orundirected according to graphChoice, and the edgesrandomly generated so as to yield an average degree of aveDegree.
    Analysis: Time = O(numVertices*aveDegree)PRECONDITION:


    ((graphChoice.charAt(0) == u) || (graphChoice.charAt(0) == U))|| (( graphChoice.charAt(0) == d)|| (graphChoice.charAt(0) == D))

    @param vertexTypeV The name of the type for the vertices of the graph@param edgeTypeE The name of the type for the edges of the graph@param numVertices The number of vertices for the graph@param aveDegree The desired average degree of the vertices@param graphChoice Indicates whether the graph is directed or indirected */

    @SuppressWarnings("unchecked")

    GraphUos(String vertexTypeV, String edgeTypeE,

    numVertices, aveDegree, String graphChoice) InvalidArgumentUosException

    {vertexType = vertexTypeV;edgeType = edgeTypeE;

    vertexArray = (V[ ]) VertexUos[numVertices]; ((graphChoice.charAt(0) == u) || (graphChoice.charAt(0) == U))

    directed = false; ((graphChoice.charAt(0) == d) || (graphChoice.charAt(0) == d))

    directed = true;

    InvalidArgumentUosException("Invalid argument--graphChoice "+ "must be directed or undirected only");

    createEdgeDataStructure();n = 0 ;

    (

    i = 1; i

  • 8/12/2019 Tremblay Chap 19

    35/106

    874 Graphs

    /** Return a new vertex whose type is given in the vertexTypeV parameter of the constructor.
    Analysis: Time = O(1)@param id The id of the new vertex */

    @SuppressWarnings("unchecked") V createNewVertex( id) InvalidArgumentUosException{

    { (V) Class.forName(vertexType).getDeclaredConstructors()[0].newInstance(id);

    } (Exception e){

    InvalidArgumentUosException("Invalid argument--vertex type "+ "in graph constructor, \nor arguments for vertex constructor."+ "\nRecall that the graph constructor must have a String parameter "+ "with the fully qualified name (specifying the package) for a "+ "vertex type, if it is not dslib.graph.VertexUos.");

    }}

    /** Return a new edge whose type is given in the edgeTypeE parameter of the constructor.
    Analysis: Time = O(1)@param v1 The starting vertex of the edge that is returned@param v2 The terminating vertex of the edge that is returned */

    @SuppressWarnings("unchecked") E createNewEdge(V v1, V v2) InvalidArgumentUosException{

    { (E) Class.forName(edgeType).getDeclaredConstructors()[0].newInstance(v1, v2);

    }

    (Exception e){

    InvalidArgumentUosException("Invalid argument--edge type "+ "in graph constructor (qualified name of type E), "+ "\n or arguments for edge contructor (two vertices of type V)."+ "\nRecall that the graph constructor must have a String parameter "+ "with the fully qualified name (specifying the package) for an "

    + "edge type, if it is not dslib.graph.EdgeUos.");}

    }

    /** Construct and insert a vertex with index id into the graph,where the index id cannot be used for any other vertex of the graph.
    Analysis: Time = O(1)
    PRECONDITION:

    !isFull()
    vertexArrayItem(id) == null

    @param id index of the new vertex */

    vNewIth( id) ContainerFullUosException,DuplicateItemsUosException

    { (isFull())

    ContainerFullUosException("Cannot add another vertex since "+ "graph is full.");

    (vertexArrayItem(id) != ) DuplicateItemsUosException("Cannot create vertex since "

    + "index id is already used");

    V newItem = createNewVertex(id);vertexArraySetItem(newItem, id);n++;

    }

    Figure 19.30. Part of the GraphUosclass (part 5)

  • 8/12/2019 Tremblay Chap 19

    36/106

    Sec. 19.5. Graph Representations 875

    /** Maximum number of vertices for the graph.
    Analysis: Time = O(1) */

    capacity(){

    vertexArray.length;}

    /** Number of vertices. */ n;

    /** Number of vertices.
    Analysis: Time = O(1)*/

    n(){

    n;}

    /** Number of edges. */ m;

    /** Number of edges.
    Analysis: Time = O(1) */

    m(){

    m;}

    /** Does the graph have any vertices?.
    Analysis: Time = O(1) */

    isEmpty(){

    n == 0;}

    /** Current item (vertex). */

    V item;

    /** Is there a current item?.
    Analysis: Time = O(1) */

    itemExists(){

    item !=

    ;}

    /** The current vertex.
    Analysis: Time = O(1)
    PRECONDITION:

    itemExists()*/

    V item() NoCurrentItemUosException{

    (!itemExists())

    NoCurrentItemUosException("There is no item to return.");

    item;}

    /** Index of the current item. */ itemIndex;

    /** Index of the current item.
    Analysis: Time = O(1) */

    itemIndex(){

    itemIndex;}

    Figure 19.30. Part of the GraphUosclass (part 6)

  • 8/12/2019 Tremblay Chap 19

    37/106

    876 Graphs

    /** Set the current vertex (item) to be newItem.
    Analysis: Time = O(1)@param newItem new vertex to be set as the current vertex */

    goToItem(V newItem){

    item = newItem;itemIndex = newItem.index;

    }

    /** Set item to refer to the vertex with index id.
    Analysis: Time = O(1)@param id index of the vertex to become current */

    goIth( id){

    itemIndex = id; (1

  • 8/12/2019 Tremblay Chap 19

    38/106

    Sec. 19.5. Graph Representations 877

    /** Construct and insert an edge with i and j as the indices of its ends.@param i index of the initial vertex of the new edge@param j index of the terminal vertex of the new edge */

    eNew( i, j){

    CursorPositionUos position = currentPosition();goIth(i);V v = item();goIth(j);eNew(v, item()); (!directed)

    eNew(item(), v);goPosition(position);

    }

    /** Construct and insert an edge with ends v1 and v2 into the graph.@param v1 initial vertex of the new edge@param v2 terminal vertex of the new edge */

    eNew(V v1, V v2);

    /** Is v1 adjacent to v2?.@param v1 vertex to check if adjacent to v2@param v2 vertex to check if adjacent to v1*/

    adjacent(V v1, V v2);/** Set eItem to refer to the edge (u,v), or null if not found.

    @param u The initial vertex of the edge being sought@param v terminal vertex of the edge being sought */

    eSearch(V u, V v);

    /** The current edge. */ E eItem;

    /** The current edge.
    Analysis: Time = O(1)
    PRECONDITION:

    eItemExists()*/

    E eItem()

    NoCurrentItemUosException

    { (!eItemExists())

    NoCurrentItemUosException("Cannot return an edge that "+ "does not exist.");

    eItem;}

    /** Is there a current edge?.
    Analysis: Time = O(1) */

    eItemExists(){

    eItem !=

    ;}

    /** The current edge.
    Analysis: Time = O(1)

    PRECONDITION:
    eItemExists()

    */ E eItem() NoCurrentItemUosException{

    (!eItemExists()) NoCurrentItemUosException("Cannot return an edge that "

    + "does not exist.");

    eItem;}

    Figure 19.30. Part of the GraphUosclass (part 8)

  • 8/12/2019 Tremblay Chap 19

    39/106

    878 Graphs

    /** Go to the first edge of v to start an edge list iteration.@param v The vertex whose first edge is to be made the current edge */

    eGoFirst(V v);

    /** Go to the next edge of the edge list being scanned.
    PRECONDITION:

    !eAfter()*/

    eGoForth() AfterTheEndUosException;

    /** Are we off the end of the edge list being scanned?. */ eAfter();

    /** Index of the vertex being edge iterated. */

    iterationIndex;

    /** Index of the vertex being edge iterated.
    Analysis: Time = O(1) */

    iterationIndex(){

    iterationIndex;}

    /** The adjacent vertex for an edge list iteration.
    Analysis: Time = O(1)
    PRECONDITION:

    eItemExists()*/

    V adjItem()

    NoCurrentItemUosException{

    (!eItemExists()) NoCurrentItemUosException("There is no adjacent item if "

    + "there is no item.");

    eItem.other(vertexArrayItem(iterationIndex));

    }

    /** The index of the adjacent vertex in the edge iteration. */ adjIndex();

    /** String representation of the graph for output.
    Analysis: Time = O(max(n, m)) */

    String toString(){

    CursorPositionUos position = currentPosition();StringBuffer result =

    StringBuffer();result.append(n); (directed)

    result.append(" directed");

    result.append(" undirected");

    Figure 19.30. Part of the GraphUosclass (part 9)

  • 8/12/2019 Tremblay Chap 19

    40/106

  • 8/12/2019 Tremblay Chap 19

    41/106

    880 Graphs

    Figure 19.21d. Provided that each vertex has a unique index, the two indices of the argu-ments for adjacent(v1, v2)can be used to access inO(1) time the location of the matrixwhich indicates whether the edge exists. Therefore, if adjacency tests are common, theadjacency matrix should be considered as a graph representation.