id
int64
0
25.6k
text
stringlengths
0
4.59k
23,100
ifrightchild currentsize &/(rightchild exists?heaparray[leftchildgetkey(heaparray[rightchildgetkey(largerchild rightchildelse largerchild leftchild/top >largerchildif(top getkey(>heaparray[largerchildgetkey()break/shift child up heaparray[indexheaparray[largerchild]index largerchild/go down /end while heaparray[indextop/index <root /end trickledown(on exiting the loop we need only restore the node stored in top to its appropriate positionpointed to by index key change after we've created the trickledown(and trickleup(methodswe can easily implement an algorithm to change the priority (the keyof node and then trickle it up or down to its proper position the change(method accomplishes thispublic boolean change(int indexint newvalueif(index=currentsizereturn falseint oldvalue heaparray[indexgetkey()/remember old heaparray[indexsetkey(newvalue)/change to new if(oldvalue newvaluetrickleup(index)else trickledown(index)return true/end change(/if raised/trickle it up /if lowered/trickle it down this routine first checks that the index given in the first argument is validand if sochanges the idata field of the node at that index to the value specified as the second argument
23,101
heaps thenif the priority has been raisedthe node is trickled upif it' been loweredit' trickled down actuallythe difficult part of changing node' priority is not shown in this routinefinding the node you want to change in the change(method just shownwe supply the index as an argumentand in the heap workshop appletthe user simply clicks on the selected node in real-world application mechanism would be needed to find the appropriate nodeas we've seenthe only node to which we normally have convenient access in heap is the one with the largest key the problem can be solved in linear (ntime by searching the array sequentially ora separate data structure (perhaps hash tablecould be updated with the new index value whenever node was moved in the priority queue this would allow quick access to any node of coursekeeping second structure updated would itself be time-consuming the array size we should note that the array sizeequivalent to the number of nodes in the heapis vital piece of information about the heap' state and critical field in the heap class nodes copied from the last position aren' erasedso the only way for algorithms to know the location of the last occupied cell is to refer to the current size of the array the heap java program the heap java programshown in listing uses node class whose only field is the idata variable that serves as the node' key as usualthis class would hold many other fields in useful program the heap class contains the methods we discussedplus isempty(and displayheap()which outputs crude but comprehensible character-based representation of the heap listing the heap java program /heap java /demonstrates heaps /to run this programc>java heapapp import java io *///////////////////////////////////////////////////////////////class node private int idata/data item (key/public node(int key/constructor
23,102
listing continued idata key/public int getkey(return idata/public void setkey(int ididata id//end class node ///////////////////////////////////////////////////////////////class heap private node[heaparrayprivate int maxsize/size of array private int currentsize/number of nodes in array /public heap(int mx/constructor maxsize mxcurrentsize heaparray new node[maxsize]/create array /public boolean isempty(return currentsize== /public boolean insert(int keyif(currentsize==maxsizereturn falsenode newnode new node(key)heaparray[currentsizenewnodetrickleup(currentsize++)return true/end insert(/public void trickleup(int indexint parent (index- node bottom heaparray[index]
23,103
listing heaps continued whileindex &heaparray[parentgetkey(bottom getkey(heaparray[indexheaparray[parent]/move it down index parentparent (parent- /end while heaparray[indexbottom/end trickleup(/public node remove(/delete item with max key /(assumes non-empty listnode root heaparray[ ]heaparray[ heaparray[--currentsize]trickledown( )return root/end remove(/public void trickledown(int indexint largerchildnode top heaparray[index]/save root while(index currentsize/ /while node has at /least one childint leftchild *index+ int rightchild leftchild+ /find larger child if(rightchild currentsize &/(rightchild exists?heaparray[leftchildgetkey(heaparray[rightchildgetkey()largerchild rightchildelse largerchild leftchild/top >largerchildiftop getkey(>heaparray[largerchildgetkey(break/shift child up heaparray[indexheaparray[largerchild]index largerchild/go down /end while heaparray[indextop/root to index
23,104
listing continued /end trickledown(/public boolean change(int indexint newvalueif(index=currentsizereturn falseint oldvalue heaparray[indexgetkey()/remember old heaparray[indexsetkey(newvalue)/change to new if(oldvalue newvalue/if raisedtrickleup(index)/trickle it up else /if loweredtrickledown(index)/trickle it down return true/end change(/public void displayheap(system out print("heaparray")/array format for(int = <currentsizem++if(heaparray[ !nullsystem out printheaparray[mgetkey(")else system out print"-")system out println()/heap format int nblanks int itemsperrow int column int /current item string dots "system out println(dots+dots)/dotted top line while(currentsize if(column = for(int = <nblanksk++system out print(')/for each heap item /first item in row/preceding blanks /display item system out print(heaparray[jgetkey())
23,105
listing heaps continued if(++ =currentsizebreak/doneif(++column==itemsperrow/end of rownblanks / /half the blanks itemsperrow * /twice the items column /start over on system out println()/new row else /next item on row for(int = <nblanks* - ++system out print(')/interim blanks /end for system out println("\ "+dots+dots)/dotted bottom line /end displayheap(//end class heap ///////////////////////////////////////////////////////////////class heapapp public static void main(string[argsthrows ioexception int valuevalue heap theheap new heap( )/make heapmax size boolean successtheheap insert( )theheap insert( )theheap insert( )theheap insert( )theheap insert( )theheap insert( )theheap insert( )theheap insert( )theheap insert( )theheap insert( )/insert items while(true/until [ctrl]-[csystem out print("enter first letter of ")
23,106
listing continued system out print("showinsertremovechange")int choice getchar()switch(choicecase ' '/show theheap displayheap()breakcase ' '/insert system out print("enter value to insert")value getint()success theheap insert(value)if!success system out println("can' insertheap full")breakcase ' '/remove if!theheap isempty(theheap remove()else system out println("can' removeheap empty")breakcase ' '/change system out print("enter current index of item")value getint()system out print("enter new key")value getint()success theheap change(valuevalue )if!success system out println("invalid index")breakdefaultsystem out println("invalid entry\ ")/end switch /end while /end main(//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return
23,107
listing heaps continued //public static char getchar(throws ioexception string getstring()return charat( )//public static int getint(throws ioexception string getstring()return integer parseint( )///end class heapapp ///////////////////////////////////////////////////////////////the array places the heap' root at index some heap implementations start the array with the root at using position as sentinel value with the largest possible key this saves an instruction in some of the algorithms but complicates things conceptually the main(routine in heapapp creates heap with maximum size of (dictated by the limitations of the display routineand inserts into it nodes with random keys then it enters loop in which the user can enter siror cfor showinsertremoveor change here' some sample interaction with the programenter first letter of showinsertremovechanges heaparray enter first letter of showinsertremovechangei enter value to insert enter first letter of showinsertremovechanges heaparray
23,108
enter first letter of showinsertremovechanger enter first letter of showinsertremovechanges heaparray enter first letter of showinsertremovechangethe user displays the heapadds an item with key of shows the heap againremoves the item with the greatest keyand shows the heap third time the show(routine displays both the array and the tree versions of the heap you'll need to use your imagination to fill in the connections between nodes expanding the heap array what happens ifwhile program is runningtoo many items are inserted for the size of the heap arraya new array can be createdand the data from the old array copied into it (unlike the situation with hash tableschanging the size of heap doesn' require reordering the data the copying operation takes linear timebut enlarging the array size shouldn' be necessary very oftenespecially if the array size is increased substantially each time it' expanded (by doubling itfor exampletip in javaa vector class object could be used instead of an arrayvectors can be expanded dynamically efficiency of heap operations for heap with substantial number of itemsthe trickle-up and trickle-down algorithms are the most time-consuming part of the operations we've seen these algorithms spend time in looprepeatedly moving nodes up or down along path the number of copies necessary is bounded by the height of the heapif there are five levelsfour copies will carry the "holefrom the top to the bottom (we'll ignore the two moves used to transfer the end node to and from temporary storagethey're always necessaryso they require constant time
23,109
heaps the trickleup(method has only one major operation in its loopcomparing the key of the new node with the node at the current location the trickledown(method needs two comparisonsone to find the largest child and second to compare this child with the "lastnode they must both copy node from top to bottom or bottom to top to complete the operation heap is special kind of binary treeand as we saw in the number of levels in binary tree equals log ( + )where is the number of nodes the trickleup(and trickledown(routines cycle through their loops - timesso the first takes time proportional to log nand the second somewhat more because of the extra comparison thusthe heap operations we've talked about here all operate in (logntime tree-based heap in the figures in this we've shown heaps as if they were trees because it' easier to visualize them that waybut the implementation has been based on an array howeverit' possible to use an actual tree-based implementation the tree will be binary treebut it won' be search tree becauseas we've seenthe ordering principle is not that strong it will also be complete treewith no missing nodes let' call such tree tree heap one problem with tree heaps is finding the last node you need to find this node to remove the maximum itembecause it' the last node that' inserted in place of the deleted root (and then trickled downyou also need to find the first empty nodebecause that' where you insert new node (and then trickle it upyou can' search for these nodes because you don' know their valuesand anyway it' not search tree howeverthese locations are not hard to find in complete tree if you keep track of the number of nodes in the tree as we saw in the discussion of the huffman tree in you can represent the path from root to leaf as binary numberwith the binary digits indicating the path from each parent to its child for left and for right it turns out there' simple relationship between the number of nodes in the tree and the binary number that codes the path to the last node assume the root is numbered the next row has nodes and the third row has nodes and and so on start with the node number you want to find this will be the last node or the first null node convert the node number to binary for examplesay there are nodes in the tree and you want to find the last node the number decimal is binary remove the initial leaving this is the path from the root to node rightrightleftright the first available null node is which (after removing the initial is binaryrightrightrightleft to carry out the calculationyou can repeatedly use the operator to find the remainder ( or when the node number is divided by and then use the
23,110
operator to actually divide by when is less than you're done the sequence of remainderswhich you can save in an array or stringis the binary number (the least significant bits correspond to the lower end of the path here' how you might calculate itwhile( > path[ ++ you could also use recursive approach in which the remainders are calculated each time the function calls itself and the appropriate direction is taken each time it returns after the appropriate node (or null childis foundthe heap operations are fairly straightforward when trickling up or downthe structure of the tree doesn' changeso you don' need to move the actual nodes around you can simply copy the data from one node to the next this wayyou don' need to connect and disconnect all the children and parents for simple move the node class will need field for the parent node because you'll need to access the parent when you trickle up we'll leave the implementation of the tree heap as programming project the tree heap operates in (logntime as in the array-based heap the time is mostly spent doing the trickle-up and trickle-down operationswhich take time proportional to the height of the tree heapsort the efficiency of the heap data structure lends itself to surprisingly simple and very efficient sorting algorithm called heapsort the basic idea is to insert all the unordered items into heap using the normal insert(routine repeated application of the remove(routine will then remove the items in sorted order here' how that might lookfor( = <sizej++theheap insertanarray[ )for( = <sizej++anarray[jtheheap remove()/from unsorted array /to sorted array because insert(and remove(operate in (logntimeand each must be applied timesthe entire sort requires ( *logntimewhich is the same as quicksort howeverit' not quite as fast as quicksortpartly because there are more operations in the inner while loop in trickledown(than in the inner loop in quicksort
23,111
heaps howeverseveral tricks can make heapsort more efficient the first saves timeand the second saves memory trickling down in place if we insert new items into heapwe apply the trickleup(method times howeverall the items can be placed in random locations in the array and then rearranged into heap with only / applications of trickledown(this offers small speed advantage two correct subheaps make correct heap to see how this approach worksyou should know that trickledown(will create correct heap ifwhen an out-of-order item is placed at the rootboth the child subheaps of this root are correct heaps (the root can itself be the root of subheap as well as of the entire heap this is shown in figure if this is correct heapand this is correct heapthenif trickledown is applied to node athis will be correct heap figure both subheaps must be correct this suggests way to transform an unordered array into heap we can apply trickledown(to the nodes on the bottom of the (potentialheap--that isat the end of the array--and work our way upward to the root at index at each step the subheaps below us will already be correct heaps because we already applied trickledown(to them after we apply trickledown(to the rootthe unordered array will have been transformed into heap noticehoweverthat the nodes on the bottom row--those with no children--are already correct heapsbecause they are trees with only one nodethey have no relationships to be out of order thereforewe don' need to apply trickledown(to these nodes we can start at node / - the rightmost node with childreninstead of - the last node thuswe need only half as many trickle operations as we would using
23,112
insert( times figure shows the order in which the trickle-down algorithm is appliedstarting at node in -node heap figure order of applying trickledown(the following code fragment applies trickledown(to all nodesexcept those on the bottom rowstarting at / - and working back to the rootfor( =size/ - >= --theheap trickledown( ) recursive approach recursive approach can also be used to form heap from an array heapify(method is applied to the root it calls itself for the root' two childrenthen for each of these children' two childrenand so on eventuallyit works its way down to the bottom rowwhere it returns immediately whenever it finds node with no children after it has called itself for two child subtreesheapify(then applies trickledown(to the root of the subtree this ensures that the subtree is correct heap then heapify(returns and works on the subtree one level higher heapify(int indexif(index / - returnheapify(index* + )heapify(index* + )trickledown(index)/transform array into heap /if node has no children/return /turn right subtree into heap /turn left subtree into heap /apply trickle-down to this node this recursive approach is probably not quite as efficient as the simple loop
23,113
heaps using the same array our initial code fragment showed unordered data in an array this data was then inserted into heapand finally removed from the heap and written back to the array in sorted order in this procedure two size- arrays are requiredthe initial array and the array used by the heap in factthe same array can be used both for the heap and for the initial array this cuts in half the amount of memory needed for heapsortno memory beyond the initial array is necessary we've already seen how trickledown(can be applied to half the elements of an array to transform them into heap we transform the unordered array data into heap in placeonly one array is necessary for this task thusthe first step in heapsort requires only one array howeverthe situation becomes more complicated when we apply remove(repeatedly to the heap where are we going to put the items that are removedeach time an item is removed from the heapan element at the end of the heap array becomes emptythe heap shrinks by one we can put the recently removed item in this newly freed cell as more items are removedthe heap array becomes smaller and smallerwhile the array of ordered data becomes larger and larger thuswith little planningit' possible for the ordered array and the heap array to share the same space this is shown in figure heap ce sorted array sorted array sorted array sorted array figure dual-purpose array sorted array
23,114
the heapsort java program we can put these two tricks--applying trickledown(without using insert()and using the same array for the initial data and the heap--together in program that performs heapsort listing shows the complete heapsort java program listing the heapsort java program /heapsort java /demonstrates heap sort /to run this programc>java heapsortapp import java io *///////////////////////////////////////////////////////////////class node private int idata/data item (key/public node(int key/constructor idata key/public int getkey(return idata//end class node ///////////////////////////////////////////////////////////////class heap private node[heaparrayprivate int maxsize/size of array private int currentsize/number of items in array /public heap(int mx/constructor maxsize mxcurrentsize heaparray new node[maxsize]/public node remove(/delete item with max key /(assumes non-empty listnode root heaparray[ ]heaparray[ heaparray[--currentsize]trickledown( )
23,115
listing heaps continued return root/end remove(/public void trickledown(int indexint largerchildnode top heaparray[index]/save root while(index currentsize/ /not on bottom row int leftchild *index+ int rightchild leftchild+ /find larger child if(rightchild currentsize &/right ch existsheaparray[leftchildgetkey(heaparray[rightchildgetkey()largerchild rightchildelse largerchild leftchild/top >largerchildif(top getkey(>heaparray[largerchildgetkey()break/shift child up heaparray[indexheaparray[largerchild]index largerchild/go down /end while heaparray[indextop/root to index /end trickledown(/public void displayheap(int nblanks int itemsperrow int column int /current item string dots "system out println(dots+dots)/dotted top line while(currentsize if(column = for(int = <nblanksk++/for each heap item /first item in row/preceding blanks
23,116
listing continued system out print(')/display item system out print(heaparray[jgetkey())if(++ =currentsizebreak/doneif(++column==itemsperrow/end of rownblanks / /half the blanks itemsperrow * /twice the items column /start over on system out println()/new row else /next item on row for(int = <nblanks* - ++system out print(')/interim blanks /end for system out println("\ "+dots+dots)/dotted bottom line /end displayheap(/public void displayarray(for(int = <maxsizej++system out print(heaparray[jgetkey(")system out println("")/public void insertat(int indexnode newnodeheaparray[indexnewnode/public void incrementsize(currentsize++//end class heap ///////////////////////////////////////////////////////////////class heapsortapp public static void main(string[argsthrows ioexception int sizej
23,117
listing heaps continued system out print("enter number of items")size getint()heap theheap new heap(size)for( = <sizej++/fill array with /random nodes int random (int)(java lang math random()* )node newnode new node(random)theheap insertat(jnewnode)theheap incrementsize()system out print("random")theheap displayarray()/display random array for( =size/ - >= --theheap trickledown( )system out print("heaptheheap displayarray()theheap displayheap()/make random array into heap ")/display heap array /display heap for( =size- >= --/remove from heap and /store at array end node biggestnode theheap remove()theheap insertat(jbiggestnode)system out print("sorted")theheap displayarray()/display sorted array /end main(/public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return //public static int getint(throws ioexception
23,118
listing continued string getstring()return integer parseint( )//end class heapsortapp the heap class is much the same as in the heap java program (listing )except that to save space we've removed the trickleup(and insert(methodswhich aren' necessary for heapsort we've also added an insertat(methodwhich allows direct insertion into the heap' array notice that this addition is not in the spirit of object-oriented programming the heap class interface is supposed to shield class users from the underlying implementation of the heap the underlying array should be invisiblebut insertat(allows direct access to it in this situation we accept the violation of oop principles because the array is so closely tied to the heap architecture an incrementsize(method is another addition to the heap class it might seem as though we could combine this with insertat()but when we're inserting into the array in its role as an ordered arraywe don' want to increase the heap sizeso we keep these functions separate the main(routine in the heapsortapp class does the following gets the array size from the user fills the array with random data turns the array into heap with / applications of trickledown( removes the items from the heap and writes them back at the end of the array after each step the array contents are displayed the user selects the array size here' some sample output from heapsort javaenter number of items random heap sorted
23,119
heaps the efficiency of heapsort as we notedheapsort runs in ( *logntime although it may be slightly slower than quicksortan advantage over quicksort is that it is less sensitive to the initial distribution of data certain arrangements of key values can reduce quicksort to slow ( timewhereas heapsort runs in ( *logntime no matter how the data is distributed summary in an ascending-priority queue the item with the largest key is said to have the highest priority (it' the smallest item in descending queue priority queue is an abstract data type (adtthat offers methods for insertion of data and removal of the largest (or smallestitem heap is an efficient implementation of an adt priority queue heap offers removal of the largest itemand insertionin ( *logntime the largest item is always in the root heaps do not support ordered traversal of the datalocating an item with specific keyor deletion heap is usually implemented as an array representing complete binary tree the root is at index and the last item at index - each node has key less than its parents and greater than its children an item to be inserted is always placed in the first vacant cell of the array and then trickled up to its appropriate position when an item is removed from the rootit' replaced by the last item in the arraywhich is then trickled down to its appropriate position the trickle-up and trickle-down processes can be thought of as sequence of swapsbut are more efficiently implemented as sequence of copies the priority of an arbitrary item can be changed firstits key is changed thenif the key was increasedthe item is trickled upbut if the key was decreasedthe item is trickled down heap can be based on binary tree (not search treethat mirrors the heap structurethis is called treeheap algorithms exist to find the last occupied node or the first free node in treeheap heapsort is an efficient sorting procedure that requires ( *logntime
23,120
conceptuallyheapsort consists of making insertions into heapfollowed by removals heapsort can be made to run faster by applying the trickle-down algorithm directly to / items in the unsorted arrayrather than inserting items the same array can be used for the initial unordered datafor the heap arrayand for the final sorted data thusheapsort requires no extra memory questions these questions are intended as self-test for readers answers may be found in appendix what does the term complete mean when applied to binary treesa all the necessary data has been inserted all the rows are filled with nodesexcept possibly the bottom one all existing nodes contain data the node arrangement satisfies the heap condition what does the term weakly ordered mean when applied to heaps node is always removed from the to "trickle upa node in descending heap means to repeatedly exchange it with its parent until it' larger than its parent to repeatedly exchange it with its child until it' larger than its child to repeatedly exchange it with its child until it' smaller than its child to repeatedly exchange it with its parent until it' smaller than its parent heap can be represented by an array because heap is complete is weakly ordered is binary tree satisfies the heap condition
23,121
heaps the last node in heap is always left child always right child always on the bottom row never less than its sibling heap is to priority queue as (nis to stack insertion into descending heap involves trickle heapsort involves removing data from heap and then inserting it again inserting data into heap and then removing it copying data from one heap to another copying data from the array representing heap to the heap how many arrayseach big enough to hold all the datadoes it take to sort heapexperiments carrying out these experiments will help to provide insights into the topics covered in the no programming is involved does the order in which data is inserted in heap affect the arrangement of the heapuse the heap workshop applet to find out use the workshop applet' ins button to insert items in ascending order into an empty heap if you remove these items with the rem buttonwill they come off in the reverse order insert some items with equal keys then remove them can you tell from this whether heapsort is stablethe color of the nodes is the secondary data item programming projects writing programs to solve the programming projects helps to solidify your understanding of the material and demonstrates how the concepts are applied (as noted in the introductionqualified instructors may obtain completed solutions to the programming projects on the publisher' web site
23,122
convert the heap java program (listing so the heap is an ascendingrather than descendingheap (that isthe node at the root is the smallest rather than the largest make sure all operations work correctly in the heap java program the insert(method inserts new node in the heap and ensures the heap condition is preserved write toss(method that places new node in the heap array without attempting to maintain the heap condition (perhaps each new item can simply be placed at the end of the array then write restoreheap(method that restores the heap condition throughout the entire heap using toss(repeatedly followed by single restoreheap(is more efficient than using insert(repeatedly when large amount of data must be inserted at one time see the description of heapsort for clues to test your programinsert few itemstoss in some moreand then restore the heap implement the priorityq class in the priorityq java program (listing using heap instead of an array you should be able to use the heap class in the heap java program (listing without modification make it descending queue (largest item is removed one problem with implementing priority queue with an array-based heap is the fixed size of the array if your data outgrows the arrayyou'll need to expand the arrayas we did for hash tables in programming project in "hash tables you can avoid this problem by implementing priority queue with an ordinary binary search tree rather than heap tree can grow as large as it wants (except for system-memory constraintsstart with the tree class from the tree java program (listing modify this class so it supports priority queues by adding removemax(method that removes the largest item in heap this is easybut in tree it' slightly harder how do you find the largest item in treedo you need to worry about both its children when you delete itimplementing change(is optional it' easily handled in binary search tree by deleting the old item and inserting new one with different key the application should relate to priorityq classthe tree class should be invisible to main((except perhaps for displaying the tree while you're debugginginsertion and removemax(will operate in (logntime write program that implements the tree heap (the tree-based implementation of the heapdiscussed in the text make sure you can remove the largest iteminsert itemsand change an item' key
23,123
graphs in this introduction to graphs searches minimum spanning trees graphs are one of the most versatile structures used in computer programming the sorts of problems that graphs can help to solve are generally quite different from those we've dealt with thus far in this book if you're dealing with general kinds of data storage problemsyou probably won' need graphbut for some problems--and they tend to be interesting ones-- graph is indispensable our discussion of graphs is divided into two in this we'll cover the algorithms associated with unweighted graphsshow some algorithms that these graphs can representand present two workshop applets to model them in the next we'll look at the more complicated algorithms associated with weighted graphs introduction to graphs graphs are data structures rather like trees in factin mathematical sensea tree is kind of graph in computer programminghowevergraphs are used in different ways than trees the data structures examined previously in this book have an architecture dictated by the algorithms used on them for examplea binary tree is shaped the way it is because that shape makes it easy to search for data and insert new data the edges in tree represent quick ways to get from node to node graphson the other handoften have shape dictated by physical or abstract problem for examplenodes in graph may represent citieswhile edges may represent airline flight routes between the cities another more abstract example is graph representing the individual topological sorting with directed graphs connectivity in directed graphs
23,124
graphs tasks necessary to complete project in the graphnodes may represent taskswhile directed edges (with an arrow at one endindicate which task must be completed before another in both casesthe shape of the graph arises from the specific realworld situation before going furtherwe must mention thatwhen discussing graphsnodes are traditionally called vertices (the singular is vertexthis is probably because the nomenclature for graphs is older than that for treeshaving arisen in mathematics centuries ago trees are more closely associated with computer science howeverboth terms are used more or less interchangeably definitions figure shows simplified map of the freeways in the vicinity of san josecalifornia figure shows graph that models these freeways in the graphcircles represent freeway interchangesand straight lines connecting the circles represent freeway segments the circles are verticesand the lines are edges the vertices are usually labeled in some way--oftenas shown herewith letters of the alphabet each edge is bounded by the two vertices at its ends the graph doesn' attempt to reflect the geographical positions shown on the mapit shows only the relationships of the vertices and the edges--that iswhich edges are connected to which vertex it doesn' concern itself with physical distances or directions alsoone edge may represent several different route numbersas in the case of the edge from to hwhich involves routes and it' the connectedness (or lack of itof one intersection to another that' importantnot the actual routes adjacency two vertices are said to be adjacent to one another if they are connected by single edge thusin figure vertices and are adjacentbut vertices and are not the vertices adjacent to given vertex are sometimes said to be its neighbors for examplethe neighbors of are ihand paths path is sequence of edges figure shows path from vertex to vertex that passes through vertices and we can call this path baej there can be more than one path between two verticesanother path from to is bcdj connected graphs graph is said to be connected if there is at least one path from every vertex to every other vertexas in the graph in figure howeverif "you can' get there from here(as vermont farmers traditionally tell city slickers who stop to ask for directions)the graph is not connectedas in figure
23,125
san francisco bay fremont milpitas palo alto aroadmap sunnyvale san jose edges vertices bgraph figure roadmap and graph non-connected graph consists of several connected components in figure ba and are one connected componentand and are another for simplicitythe algorithms we'll be discussing in this are written to apply to connected graphsor to one connected component of non-connected graph if appropriatesmall modifications will usually enable them to work with nonconnected graphs as well
23,126
graphs figure aconnected graph bnon-connected graph connected and non-connected graphs directed and weighted graphs the graphs in figures and are non-directed graphs that means that the edges don' have directionyou can go either way on them thusyou can go from vertex to vertex bor from vertex to vertex awith equal ease (non-directed graphs model freeways appropriatelybecause you can usually go either way on freeway howevergraphs are often used to model situations in which you can go in only one direction along an edge--from to but not from to aas on one-way street such graph is said to be directed the allowed direction is typically shown with an arrowhead at the end of the edge in some graphsedges are given weighta number that can represent the physical distance between two verticesor the time it takes to get from one vertex to anotheror how much it costs to travel from vertex to vertex (on airline routesfor examplesuch graphs are called weighted graphs we'll explore them in the next we're going to begin this by discussing simple undirectedunweighted graphslater we'll explore directed unweighted graphs we have by no means covered all the definitions that apply to graphswe'll introduce more as we go along historical note one of the first mathematicians to work with graphs was leonhard euler in the early eighteenth century he solved famous problem dealing with the bridges in the town of konigsbergpoland this town included an island and seven bridgesas shown in figure the problemmuch discussed by the townsfolkwas to find way to walk across all seven bridges without recrossing any of them we won' recount euler' solution to the problemit turns out that there is no such path howeverthe key to his solution was to represent the problem as graphwith land areas as vertices and bridges as
23,127
edgesas shown in figure this is perhaps the first example of graph being used to represent problem in the real world amap vertex edge bgraph figure the bridges of konigsberg representing graph in program it' all very well to think about graphs in the abstractas euler and other mathematicians did until the invention of the computerbut we want to represent graphs by using computer what sort of software structures are appropriate to model graphwe'll look at vertices first and then at edges vertices in very abstract graph program you could simply number the vertices to - (where is the number of verticesyou wouldn' need any sort of variable to hold the vertices because their usefulness would result from their relationships with other vertices in most situationshowevera vertex represents some real-world objectand the object must be described using data items if vertex represents city in an airline route simulationfor exampleit may need to store the name of the cityits altitudeits locationand other such information thusit' usually convenient to represent vertex by an object of vertex class our example programs store only letter (like )used as label for identifying the vertexand flag for use in search algorithmsas we'll see later here' how the vertex class looks
23,128
graphs class vertex public char label/label ( ' 'public boolean wasvisitedpublic vertex(char lablabel labwasvisited false/end class vertex /constructor vertex objects can be placed in an array and referred to using their index number in our examples we'll store them in an array called vertexlist the vertices might also be placed in list or some other data structure whatever structure is usedthis storage is for convenience only it has no relevance to how the vertices are connected by edges for thiswe need another mechanism edges in "red-black trees,we saw that computer program can represent trees in several ways mostly we examined trees in which each node contained references to its childrenbut we also mentioned that an array could be usedwith node' position in the array indicating its relationship to other nodes "heaps,described arrays used to represent kind of tree called heap graphhoweverdoesn' usually have the same kind of fixed organization as tree in binary treeeach node has maximum of two childrenbut in graph each vertex may be connected to an arbitrary number of other vertices for examplein figure avertex is connected to three other verticeswhereas is connected to only one to model this sort of free-form organizationa different approach to representing edges is preferable to that used for trees two methods are commonly used for graphsthe adjacency matrix and the adjacency list (remember that one vertex is said to be adjacent to another if they're connected by single edge the adjacency matrix an adjacency matrix is two-dimensional array in which the elements indicate whether an edge is present between two vertices if graph has verticesthe adjacency matrix is an nxn array table shows the adjacency matrix for the graph in figure
23,129
table adjacency matrix the vertices are used as headings for both rows and columns an edge between two vertices is indicated by the absence of an edge is (you could also use boolean true/false values as you can seevertex is adjacent to all three other verticesb is adjacent to and dc is adjacent only to aand is adjacent to and in this examplethe "connectionof vertex to itself is indicated by so the diagonal from upper left to lower righta- to -dwhich is called the identity diagonalis all the entries on the identity diagonal don' convey any real informationso you can equally well put along itif that' more convenient in your program note that the triangular-shaped part of the matrix above the identity diagonal is mirror image of the part belowboth triangles contain the same information this redundancy may seem inefficientbut there' no convenient way to create triangular array in most computer languagesso it' simpler to accept the redundancy consequentlywhen you add an edge to the graphyou must make two entries in the adjacency matrix rather than one the adjacency list the other way to represent edges is with an adjacency list the list in adjacency list refers to linked list of the kind we examined in "linked lists actuallyan adjacency list is an array of lists (or sometimes list of listseach individual list shows what vertices given vertex is adjacent to table shows the adjacency lists for the graph of figure table adjacency lists vertex list containing adjacent vertices --> --> --> --> in this tablethe --symbol indicates link in linked list each link in the list is vertex here the vertices are arranged in alphabetical order in each listalthough that' not really necessary don' confuse the contents of adjacency lists with paths the adjacency list shows which vertices are adjacent to--that isone edge away from-- given vertexnot paths from vertex to vertex
23,130
graphs later we'll discuss when to use an adjacency matrix as opposed to an adjacency list the workshop applets shown in this all use the adjacency matrix approachbut sometimes the list approach is more efficient adding vertices and edges to graph to add vertex to graphyou make new vertex object with new and insert it into your vertex arrayvertexlist in real-world program vertex might contain many data itemsbut for simplicity we'll assume that it contains only single character thusthe creation of vertex looks something like thisvertexlist[nverts++new vertex(' ')this inserts vertex fwhere nverts is the number of vertices currently in the graph how you add an edge to graph depends on whether you're using an adjacency matrix or adjacency lists to represent the graph let' say that you're using an adjacency matrix and want to add an edge between vertices and these numbers correspond to the array indices in vertexlist where the vertices are stored when you first created the adjacency matrix adjmatyou filled it with to insert the edgeyou say adjmat[ ][ adjmat[ ][ if you were using an adjacency listyou would add to the list for and to the list for the graph class let' look at class graph that contains methods for creating vertex list and an adjacency matrixand for adding vertices and edges to graph objectclass graph private final int max_verts private vertex vertexlist[]/array of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices /public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]
23,131
nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][ /end constructor /public void addvertex(char lab/argument is label vertexlist[nverts++new vertex(lab)/public void addedge(int startint endadjmat[start][end adjmat[end][start /public void displayvertex(int vsystem out print(vertexlist[vlabel)//end class graph within the graph classvertices are identified by their index number in vertexlist we've already discussed most of the methods shown here to display vertexwe simply print out its one-character label the adjacency matrix (or the adjacency listprovides information that is local to given vertex specificallyit tells you which vertices are connected by single edge to given vertex to answer more global questions about the arrangement of the verticeswe must resort to various algorithms we'll begin with searches searches one of the most fundamental operations to perform on graph is finding which vertices can be reached from specified vertex for exampleimagine trying to find out how many towns in the united states can be reached by passenger train from kansas city (assuming that you don' mind changing trainssome towns could be reached others couldn' be reached because they didn' have passenger rail service possibly others couldn' be reachedeven though they had rail servicebecause their rail system (the narrow-gauge hayfork-hicksville rrfor exampledidn' connect
23,132
graphs with the standard-gauge line you started on or any of the lines that could be reached from your line here' another situation in which you might need to find all the vertices reachable from specified vertex imagine that you're designing printed circuit boardlike the ones inside your computer (open it up and take look!various components-mostly integrated circuits (ics)--are placed on the boardwith pins from the ics protruding through holes in the board the ics are soldered in placeand their pins are electrically connected to other pins by traces--thin metal lines applied to the surface of the circuit boardas shown in figure (noyou don' need to worry about the details of this figure pins traces figure pins and traces on circuit board in grapheach pin might be represented by vertexand each trace by an edge on circuit board there are many electrical circuits that aren' connected to each otherso the graph is by no means connected one during the design processthereforeit may be genuinely useful to create graph and use it to find which pins are connected to the same electrical circuit assume that you've created such graph now you need an algorithm that provides systematic way to start at specified vertex and then move along edges to other vertices in such way thatwhen it' doneyou are guaranteed that it has visited every vertex that' connected to the starting vertex hereas it did in "binary trees,where we discussed binary treesvisit means to perform some operation on the vertexsuch as displaying it there are two common approaches to searching graphdepth-first search (dfsand breadth-first search (bfsboth will eventually reach all connected vertices the depth-first search is implemented with stackwhereas the breadth-first search is
23,133
implemented with queue these mechanisms resultas we'll seein the graph being searched in different ways depth-first search the depth-first search uses stack to remember where it should go when it reaches dead end we'll show an exampleencourage you to try similar examples with the graphn workshop appletand then finally show some code that carries out the search an example we'll discuss the idea behind the depth-first search in relation to figure the numbers in this figure show the order in which the vertices are visited figure depth-first search to carry out the depth-first searchyou pick starting point--in this casevertex you then do three thingsvisit this vertexpush it onto stack so you can remember itand mark it so you won' visit it again nextyou go to any vertex adjacent to that hasn' yet been visited we'll assume the vertices are selected in alphabetical orderso that brings up you visit bmark itand push it on the stack now whatyou're at band you do the same thing as beforego to an adjacent vertex that hasn' been visited this leads you to we can call this process rule rule if possiblevisit an adjacent unvisited vertexmark itand push it on the stack applying rule again leads you to at this pointhoweveryou need to do something else because there are no unvisited vertices adjacent to here' where rule comes in
23,134
graphs rule if you can' follow rule thenif possiblepop vertex off the stack following this ruleyou pop off the stackwhich brings you back to has no unvisited adjacent verticesso you pop it ditto now only is left on the stack ahoweverdoes have unvisited adjacent verticesso you visit the next onec but is the end of the line againso you pop it and you're back to you visit dgand iand then pop them all when you reach the dead end at now you're back to you visit eand again you're back to this timehowevera has no unvisited neighborsso we pop it off the stack but now there' nothing left to popwhich brings up rule rule if you can' follow rule or rule you're done table shows how the stack looks in the various stages of this processas applied to figure table stack contents during depth-first search event stack visit visit visit visit pop pop pop visit pop visit visit visit pop pop pop visit pop pop ab abf abfh abf ab ac ad adg adgi adg ad ae done
23,135
the contents of the stack is the route you took from the starting vertex to get where you are as you move away from the starting vertexyou push vertices as you go as you move back toward the starting vertexyou pop them the order in which you visit the vertices is abfhcdgie you might say that the depth-first search algorithm likes to get as far away from the starting point as quickly as possible and returns only when it reaches dead end if you use the term depth to mean the distance from the starting pointyou can see where the name depth-first search comes from an analogy an analogy you might think about in relation to depth-first search is maze the maze--perhaps one of the people-size ones made of hedgespopular in england-consists of narrow passages (think of edgesand intersections where passages meet (verticessuppose that someone is lost in the maze she knows there' an exit and plans to traverse the maze systematically to find it fortunatelyshe has ball of string and marker pen she starts at some intersection and goes down randomly chosen passageunreeling the string at the next intersectionshe goes down another randomly chosen passageand so onuntil finally she reaches dead end at the dead end she retraces her pathreeling in the stringuntil she reaches the previous intersection here she marks the path she' been down so she won' take it againand tries another path when she' marked all the paths leading from that intersectionshe returns to the previous intersection and repeats the process the string represents the stackit "remembersthe path taken to reach certain point the graphn workshop applet and dfs you can try out the depth-first search with the dfs button in the graphn workshop applet (the is for not directednot weighted start the applet at the beginningthere are no vertices or edgesjust an empty rectangle you create vertices by double-clicking the desired location the first vertex is automatically labeled athe second one is band so on they're colored randomly to make an edgedrag from one vertex to another figure shows the graph of figure as it looks when created using the applet there' no way to delete individual edges or verticesso if you make mistakeyou'll need to start over by clicking the new buttonwhich erases all existing vertices and edges (it warns you before it does this clicking the view button switches you to the adjacency matrix for the graph you've madeas shown in figure clicking view again switches you back to the graph
23,136
graphs figure the graphn workshop applet figure adjacency matrix view in graphn to run the depth-first search algorithmclick the dfs button repeatedly you'll be prompted to click (not double-clickthe starting vertex at the beginning of the process you can re-create the graph of figure or you can create simpler or more complex ones of your own after you play with it whileyou can predict what the algorithm will do next (unless the graph is too weirdif you use the algorithm on an unconnected graphit will find only those vertices that are connected to the starting vertex
23,137
java code key to the dfs algorithm is being able to find the vertices that are unvisited and adjacent to specified vertex how do you do thisthe adjacency matrix is the key by going to the row for the specified vertex and stepping across the columnsyou can pick out the columns with the column number is the number of an adjacent vertex you can then check whether this vertex is unvisited if soyou've found what you want--the next vertex to visit if no vertices on the row are simultaneously (adjacentand also unvisitedthere are no unvisited vertices adjacent to the specified vertex we put the code for this process in the getadjunvisitedvertex(method/returns an unvisited vertex adjacent to public int getadjunvisitedvertex(int vfor(int = <nvertsj++if(adjmat[ ][ ]== &vertexlist[jwasvisited==falsereturn /return first such vertex return - /no such vertices /end getadjunvisitedvertex(now we're ready for the dfs(method of the graph classwhich actually carries out the depth-first search you can see how this code embodies the three rules listed earlier it loops until the stack is empty within the loopit does four things it examines the vertex at the top of the stackusing peek( it tries to find an unvisited neighbor of this vertex if it doesn' find oneit pops the stack if it finds such vertexit visits that vertex and pushes it onto the stack here' the code for the dfs(methodpublic void dfs(/depth-first search /begin at vertex vertexlist[ wasvisited true/mark it displayvertex( )/display it thestack push( )/push it while!thestack isempty(/until stack empty/get an unvisited vertex adjacent to stack top int getadjunvisitedvertexthestack peek()if( =- /if no such vertexthestack pop()/pop new one
23,138
graphs else /if it existsvertexlist[vwasvisited true/mark it displayvertex( )/display it thestack push( )/push it /end while /stack is emptyso we're done for(int = <nvertsj++/reset flags vertexlist[jwasvisited false/end dfs at the end of dfs()we reset all the wasvisited flags so we'll be ready to run dfs(again later the stack should already be emptyso it doesn' need to be reset now we have all the pieces of the graph class we need here' some code that creates graph objectadds some vertices and edges to itand then performs depth-first searchgraph thegraph new graph()thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )(start for dfs/ab /bc /ad /de system out print("visits")thegraph dfs()/depth-first search system out println()figure shows the graph created by this code here' the outputvisitsabcde you can modify this code to create the graph of your choiceand then run it to see it carry out the depth-first search
23,139
figure graph used by dfs java and bfs java the dfs java program listing shows the dfs java programwhich includes the dfs(method it includes version of the stackx class from "stacks and queues listing the dfs java program /dfs java /demonstrates depth-first search /to run this programc>java dfsapp ///////////////////////////////////////////////////////////////class stackx private final int size private int[stprivate int top/public stackx(/constructor st new int[size]/make array top - /public void push(int /put item on stack st[++topj/public int pop(/take item off stack return st[top--]/public int peek(/peek at top of stack
23,140
listing graphs continued return st[top]/public boolean isempty(/true if nothing on stackreturn (top =- )//end class stackx ///////////////////////////////////////////////////////////////class vertex public char label/label ( ' 'public boolean wasvisited/public vertex(char lab/constructor label labwasvisited false//end class vertex ///////////////////////////////////////////////////////////////class graph private final int max_verts private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private stackx thestack/public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][ thestack new stackx()/end constructor /public void addvertex(char lab
23,141
listing continued vertexlist[nverts++new vertex(lab)/public void addedge(int startint endadjmat[start][end adjmat[end][start /public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void dfs(/depth-first search /begin at vertex vertexlist[ wasvisited true/mark it displayvertex( )/display it thestack push( )/push it while!thestack isempty(/until stack empty/get an unvisited vertex adjacent to stack top int getadjunvisitedvertexthestack peek()if( =- /if no such vertexthestack pop()else /if it existsvertexlist[vwasvisited true/mark it displayvertex( )/display it thestack push( )/push it /end while /stack is emptyso we're done for(int = <nvertsj++/reset flags vertexlist[jwasvisited false/end dfs //returns an unvisited vertex adj to
23,142
listing graphs continued public int getadjunvisitedvertex(int vfor(int = <nvertsj++if(adjmat[ ][ ]== &vertexlist[jwasvisited==falsereturn jreturn - /end getadjunvisitedvertex(//end class graph ///////////////////////////////////////////////////////////////class dfsapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (start for dfsthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /bc /ad /de system out print("visits")thegraph dfs()/depth-first search system out println()/end main(/end class dfsapp ///////////////////////////////////////////////////////////////depth-first search and game simulations depth-first searches are often used in simulations of games (and game-like situations in the real worldin typical game you can choose one of several possible actions each choice leads to further choiceseach of which leads to further choicesand so on into an ever-expanding tree-shaped graph of possibilities choice point corresponds to vertexand the specific choice taken corresponds to an edgewhich leads to another choice-point vertex
23,143
imagine game of tic-tac-toe if you go firstyou can make one of nine possible moves your opponent can counter with one of eight possible movesand so on each move leads to another group of choices by your opponentwhich leads to another series of choices for youuntil the last square is filled when you are deciding what move to makeone approach is to mentally imagine movethen your opponent' possible responsesthen your responsesand so on you can decide what to do by seeing which move leads to the best outcome in simple games like tic-tac-toe the number of possible moves is sufficiently limited that it' possible to follow each path to the end of the game after you've analyzed the paths completelyyou know which move to make first this can be represented by graph with one node representing your first movewhich is connected to eight nodes representing your opponent' possible responseseach of which is connected to seven nodes representing your responsesand so on all these paths from the beginning node to an end node include nine nodes for complete analysis you'll need to draw nine graphsone for each starting move even in this simple game the number of paths is surprisingly large if we ignore simplifications from symmetrythere are * * * * * * * * paths in the nine graphs this is factorial ( !or , in game like chess where the number of possible moves is much greatereven the most powerful computers (like ibm' "deep blue"cannot "seeto the end of the game they can only follow path to certain depth and then evaluate the board to see if it appears more favorable than other choices the natural way to examine such situations in computer program is to use depthfirst search at each node you decide what move to make nextas is done in the getadjunvisitedvertex(method in the dfs java program (listing if there are still unvisited nodes (choice points)you push the current one on the stack and go on to the next if you find you can' make move (getadjunvisitedvertex(returns - in certain situationyou backtrack by popping node off the stack (which corresponds to taking back moveand see if the resulting position has any unexplored choices you can think of the sequences of moves in game as treewith nodes representing moves the first move is the root in tic-tac-toeafter the first move there are eight possible second moveseach represented by node connected to the root after each of these eight second movesthere are seven possible third moves represented by nodes connected to the second-move nodes you end up with tree with possible paths from the root to the leaves this is called the game tree actuallythe number of branches in the game tree is reduced because the game is often won before all the squares are filled howeverthe tic-tac-toe game tree is still very large and complexand this is simple game compared with many otherssuch as chess
23,144
graphs only some paths in game tree lead to successful conclusion for examplesome lead to win by your opponent when you reach such an endingyou must back upor backtrackto previous node and try different path in this way you explore the tree until you find path with successful conclusion then you make the first move along this path breadth-first search as we saw in the depth-first searchthe algorithm acts as though it wants to get as far away from the starting point as quickly as possible in the breadth-first searchon the other handthe algorithm likes to stay as close as possible to the starting point it visits all the vertices adjacent to the starting vertexand only then goes further afield this kind of search is implemented using queue instead of stack an example figure shows the same graph as figure but here the breadth-first search is used againthe numbers indicate the order in which the vertices are visited figure breadth-first search is the starting vertexso you visit it and make it the current vertex then you follow these rulesrule visit the next unvisited vertex (if there is onethat' adjacent to the current vertexmark itand insert it into the queue rule if you can' carry out rule because there are no more unvisited verticesremove vertex from the queue (if possibleand make it the current vertex
23,145
rule if you can' carry out rule because the queue is emptyyou're done thusyou first visit all the vertices adjacent to ainserting each one into the queue as you visit it now you've visited abcdand at this point the queue (from front to rearcontains bcde there are no more unvisited vertices adjacent to aso you remove from the queue and look for vertices adjacent to it you find fso you insert it in the queue there are no more unvisited vertices adjacent to bso you remove from the queue it has no adjacent unvisited verticesso you remove and visit has no more adjacent unvisited verticesso you remove now the queue is fg you remove and visit hand then you remove and visit now the queue is hibut when you've removed each of these and found no adjacent unvisited verticesthe queue is emptyso you're done table shows this sequence table event visit visit visit visit visit remove visit remove remove visit remove remove visit remove visit remove remove done queue contents during breadth-first search queue (front to rearb bc bcd bcde cde cdef def ef efg fg gh hi at each momentthe queue contains the vertices that have been visited but whose neighbors have not yet been fully explored (contrast this breadth-first search with the depth-first searchwhere the contents of the stack is the route you took from the starting point to the current vertex the nodes are visited in the order abcdefghi
23,146
graphs the graphn workshop applet and bfs use the graphn workshop applet to try out breadth-first search using the bfs button againyou can experiment with the graph of figure or you can make up your own notice the similarities and the differences of the breadth-first search compared with the depth-first search you can think of the breadth-first search as proceeding like ripples widening when you drop stone in water--orfor those of you who enjoy epidemiologyas the influenza virus carried by air travelers from city to city firstall the vertices one edge (plane flightaway from the starting point are visitedthen all the vertices two edges away are visitedand so on java code the bfs(method of the graph class is similar to the dfs(methodexcept that it uses queue instead of stack and features nested loops instead of single loop the outer loop waits for the queue to be emptywhereas the inner one looks in turn at each unvisited neighbor of the current vertex here' the codepublic void bfs(/breadth-first search /begin at vertex vertexlist[ wasvisited true/mark it displayvertex( )/display it thequeue insert( )/insert at tail int while!thequeue isempty(/until queue emptyint thequeue remove()/remove vertex at head /until it has no unvisited neighbors while( =getadjunvisitedvertex( )!- /get onevertexlist[ wasvisited true/mark it displayvertex( )/display it thequeue insert( )/insert it /end while(unvisited neighbors/end while(queue not empty/queue is emptyso we're done for(int = <nvertsj++vertexlist[jwasvisited false/end bfs(/reset flags
23,147
given the same graph as in dfs java (shown earlier in figure )the output from bfs java is now visitsabdce the bfs java program the bfs java programshown in listing is similar to dfs java except for the inclusion of queue class (modified from the version in instead of stackx classand bfs(method instead of dfs(method listing the bfs java program /bfs java /demonstrates breadth-first search /to run this programc>java bfsapp ///////////////////////////////////////////////////////////////class queue private final int size private int[quearrayprivate int frontprivate int rear/public queue(/constructor quearray new int[size]front rear - /public void insert(int /put item at rear of queue if(rear =size- rear - quearray[++rearj/public int remove(/take item from front of queue int temp quearray[front++]if(front =sizefront return temp
23,148
listing graphs continued /public boolean isempty(/true if queue is empty return rear+ ==front |(front+size- ==rear)//end class queue ///////////////////////////////////////////////////////////////class vertex public char label/label ( ' 'public boolean wasvisited/public vertex(char lab/constructor label labwasvisited false//end class vertex ///////////////////////////////////////////////////////////////class graph private final int max_verts private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private queue thequeue/public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][ thequeue new queue()/end constructor
23,149
listing continued /public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endadjmat[start][end adjmat[end][start /public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void bfs(/breadth-first search /begin at vertex vertexlist[ wasvisited true/mark it displayvertex( )/display it thequeue insert( )/insert at tail int while!thequeue isempty(/until queue emptyint thequeue remove()/remove vertex at head /until it has no unvisited neighbors while( =getadjunvisitedvertex( )!- /get onevertexlist[ wasvisited true/mark it displayvertex( )/display it thequeue insert( )/insert it /end while /end while(queue not empty/queue is emptyso we're done for(int = <nvertsj++/reset flags vertexlist[jwasvisited false/end bfs(/
23,150
listing graphs continued /returns an unvisited vertex adj to public int getadjunvisitedvertex(int vfor(int = <nvertsj++if(adjmat[ ][ ]== &vertexlist[jwasvisited==falsereturn jreturn - /end getadjunvisitedvertex(//end class graph ///////////////////////////////////////////////////////////////class bfsapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (start for dfsthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /bc /ad /de system out print("visits")thegraph bfs()/breadth-first search system out println()/end main(/end class bfsapp ///////////////////////////////////////////////////////////////the breadth-first search has an interesting propertyit first finds all the vertices that are one edge away from the starting pointthen all the vertices that are two edges awayand so on this is useful if you're trying to find the shortest path from the starting vertex to given vertex you start bfsand when you find the specified vertexyou know the path you've traced so far is the shortest path to the node if there were shorter paththe bfs would have found it already
23,151
minimum spanning trees suppose that you've designed printed circuit board like the one shown in figure and you want to be sure you've used the minimum number of traces that isyou don' want any extra connections between pinssuch extra connections would take up extra room and make other circuits more difficult to lay out it would be nice to have an algorithm thatfor any connected set of pins and traces (vertices and edgesin graph terminology)would remove any extra traces the result would be graph with the minimum number of edges necessary to connect the vertices for examplefigure shows five vertices with an excessive number of edgeswhile figure shows the same vertices with the minimum number of edges necessary to connect them this constitutes minimum spanning tree (msta aextra edges figure bminimum number of edges minimum spanning tree there are many possible minimum spanning trees for given set of vertices figure shows edges abbccdand debut edges acceedand db would do just as well the arithmetically inclined will note that the number of edges in minimum spanning tree is always one less than the number of vertices ve= - remember that we're not worried here about the length of the edges we're not trying to find minimum physical lengthjust the minimum number of edges (this will change when we talk about weighted graphs in the next the algorithm for creating the minimum spanning tree is almost identical to that used for searching it can be based on either the depth-first search or the breadthfirst search in our example we'll use the depth-first search perhaps surprisinglyby executing the depth-first search and recording the edges you've traveled to make the searchyou automatically create minimum spanning tree the only difference between the minimum spanning tree method mst()which we'll see in momentand the depth-first search method dfs()which we saw earlieris that mst(must somehow record the edges traveled
23,152
graphs graphn workshop applet repeatedly clicking the tree button in the graphn workshop algorithm will create minimum spanning tree for any graph you create try it out with various graphs you'll see that the algorithm follows the same steps as when using the dfs button to do search when you use treehoweverthe appropriate edge is darkened when the algorithm assigns it to the minimum spanning tree when the algorithm is finishedthe applet removes all the non-darkened linesleaving only the minimum spanning tree final button press restores the original graphin case you want to use it again java code for the minimum spanning tree here' the code for the mst(methodwhile!thestack isempty(/until stack empty /get stack top int currentvertex thestack peek()/get next unvisited neighbor int getadjunvisitedvertex(currentvertex)if( =- /if no more neighbors thestack pop()/pop it away else /got neighbor vertexlist[vwasvisited true/mark it thestack push( )/push it /display edge displayvertex(currentvertex)/from currentv displayvertex( )/to system out print(")/end while(stack not empty/stack is emptyso we're done for(int = <nvertsj++/reset flags vertexlist[jwasvisited false/end mst(as you can seethis code is very similar to dfs(in the else statementhoweverthe current vertex and its next unvisited neighbor are displayed these two vertices define the edge that the algorithm is currently traveling to get to new vertexand it' these edges that make up the minimum spanning tree in the main(part of the mst java programwe create graph by using these statements
23,153
graph thegraph new graph()thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )(start for mst/ab /ac /ad /ae /bc /bd /be /cd /ce /de the graph that results is the one shown in figure when the mst(method has done its workonly four edges are leftas shown in figure here' the output from the mst java programminimum spanning treeab bc cd de as we notedthis is only one of many possible minimum scanning trees that can be created from this graph using different starting vertexfor examplewould result in different tree so would small variations in the codesuch as starting at the end of the vertexlist[instead of the beginning in the getadjunvisitedvertex(method the minimum spanning tree is easily derived from the depth-first search because the dfs visits all the nodesbut only once it never goes to node that has already been visited when it looks down an edge that has visited node at the endit doesn' follow that edge it never travels any edges that aren' necessary thusthe path of the dfs algorithm through the graph must be minimum spanning tree the mst java program listing shows the mst java program it' similar to dfs javaexcept for the mst(method and the graph created in main(listing the mst java program /mst java /demonstrates minimum spanning tree /to run this programc>java mstapp ///////////////////////////////////////////////////////////////
23,154
listing graphs continued class stackx private final int size private int[stprivate int top/public stackx(/constructor st new int[size]/make array top - /public void push(int /put item on stack st[++topj/public int pop(/take item off stack return st[top--]/public int peek(/peek at top of stack return st[top]/public boolean isempty(/true if nothing on stack return (top =- )//end class stackx ///////////////////////////////////////////////////////////////class vertex public char label/label ( ' 'public boolean wasvisited/public vertex(char lab/constructor label labwasvisited false//end class vertex ///////////////////////////////////////////////////////////////class graph
23,155
listing continued private final int max_verts private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private stackx thestack/public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][ thestack new stackx()/end constructor /public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endadjmat[start][end adjmat[end][start /public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void mst(/minimum spanning tree (depth first/start at vertexlist[ wasvisited true/mark it thestack push( )/push it while!thestack isempty(/until stack empty /get stack top
23,156
listing graphs continued int currentvertex thestack peek()/get next unvisited neighbor int getadjunvisitedvertex(currentvertex)if( =- /if no more neighbors thestack pop()/pop it away else /got neighbor vertexlist[vwasvisited true/mark it thestack push( )/push it /display edge displayvertex(currentvertex)/from currentv displayvertex( )/to system out print(")/end while(stack not empty/stack is emptyso we're done for(int = <nvertsj++/reset flags vertexlist[jwasvisited false/end tree //returns an unvisited vertex adj to public int getadjunvisitedvertex(int vfor(int = <nvertsj++if(adjmat[ ][ ]== &vertexlist[jwasvisited==falsereturn jreturn - /end getadjunvisitedvertex(//end class graph ///////////////////////////////////////////////////////////////class mstapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (start for mstthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/
23,157
listing continued thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ab /ac /ad /ae /bc /bd /be /cd /ce /de system out print("minimum spanning tree")thegraph mst()/minimum spanning tree system out println()/end main(/end class mstapp ///////////////////////////////////////////////////////////////the statements in main(form graph that can be visualized as five-pointed star with every node connected to every other node the output is minimum spanning treeab bc cd de topological sorting with directed graphs topological sorting is another operation that can be modeled with graphs it' useful in situations in which items or events must be arranged in specific order let' look at an example an examplecourse prerequisites in high school and collegestudents find (sometimes to their dismaythat they can' take just any course they want some courses have prerequisites--other courses that must be taken first indeedtaking certain courses may be prerequisite to obtaining degree in certain field figure shows somewhat fanciful arrangement of courses necessary for graduating with degree in mathematics
23,158
graphs algebra advanced algebra senior seminar geometry analytic geometry english comp figure degree comparative literature course prerequisites to obtain your degreeyou must complete the senior seminar and (because of pressure from the english departmentcomparative literature but you can' take senior seminar without having already taken advanced algebra and analytic geometryand you can' take comparative literature without taking english composition alsoyou need geometry for analytic geometryand algebra for both advanced algebra and analytic geometry directed graphs as figure showsa graph can represent this sort of arrangement howeverthe graph needs feature we haven' seen beforethe edges need to have direction when this is the casethe graph is called directed graph in directed graph you can proceed only one way along an edge the arrows in the figure show the direction of the edges in programthe difference between non-directed graph and directed graph is that an edge in directed graph has only one entry in the adjacency matrix figure shows small directed graphtable shows its adjacency matrix figure small directed graph
23,159
table adjacency matrix for small directed graph each edge is represented by single the row labels show where the edge startsand the column labels show where it ends thusthe edge from to is represented by single at row column if the directed edge were reversed so that it went from to athere would be at row column instead for non-directed graphas we noted earlierhalf of the adjacency matrix mirrors the other halfso half the cells are redundant howeverfor weighted graphevery cell in the adjacency matrix conveys unique information the halves are not mirror images for directed graphthe method that adds an edge thus needs only single statementpublic void addedge(int startint endadjmat[start][end /directed graph instead of the two statements required in non-directed graph if you use the adjacency-list approach to represent your graphthen has in its list but--unlike non-directed graph-- does not have in its list topological sorting imagine that you make list of all the courses necessary for your degreeusing figure as your input data you then arrange the courses in the order you need to take them obtaining your degree is the last item on the listwhich might look like thisbaedgcfh arranged this waythe graph is said to be topologically sorted any course you must take before some other course occurs before it in the list actuallymany possible orderings would satisfy the course prerequisites you could take the english courses and firstfor examplecfbaedgh
23,160
graphs this also satisfies all the prerequisites there are many other possible orderings as well when you use an algorithm to generate topological sortthe approach you take and the details of the code determine which of various valid sortings are generated topological sorting can model other situations besides course prerequisites job scheduling is an important example if you're building caryou want to arrange things so that brakes are installed before the wheelsand the engine is assembled before it' bolted onto the chassis car manufacturers use graphs to model the thousands of operations in the manufacturing processto ensure that everything is done in the proper order modeling job schedules with graphs is called critical path analysis although we don' show it herea weighted graph (discussed in the next can be usedwhich allows the graph to include the time necessary to complete different tasks in project the graph can then tell you such things as the minimum time necessary to complete the entire project the graphd workshop applet the graphd workshop applet models directed graphs this applet operates in much the same way as graphn but provides dot near one end of each edge to show which direction the edge is pointing be carefulthe direction you drag the mouse to create the edge determines the direction of the edge figure shows the graphd workshop applet used to model the course-prerequisite situation of figure figure the graphd workshop applet
23,161
the idea behind the topological sorting algorithm is unusual but simple two steps are necessarystep find vertex that has no successors the successors to vertex are those vertices that are directly "downstreamfrom it-that isconnected to it by an edge that points in their direction if there is an edge pointing from to bthen is successor to in figure the only vertex with no successors is step delete this vertex from the graphand insert its label at the beginning of list steps and are repeated until all the vertices are gone at this pointthe list shows the vertices arranged in topological order you can see the process at work by using the graphd applet construct the graph of figure (or any other graphif you preferby double-clicking to make vertices and dragging to make edges then repeatedly click the topo button as each vertex is removedits label is placed at the beginning of the list below the graph deleting vertex may seem like drastic stepbut it' the heart of the algorithm the algorithm can' figure out the second vertex to remove until the first vertex is gone if you need toyou can save the graph' data (the vertex list and the adjacency matrixelsewhere and restore it when the sort is completedas we do in the graphd applet the algorithm works because if vertex has no successorsit must be the last one in the topological ordering as soon as it' removedone of the remaining vertices must have no successorsso it will be the next-to-last one in the orderingand so on the topological sorting algorithm works on unconnected graphs as well as connected graphs this models the situation in which you have two unrelated goalssuch as getting degree in mathematics and at the same time obtaining certificate in first aid cycles and trees one kind of graph the topological-sort algorithm cannot handle is graph with cycles what' cycleit' path that ends up where it started in figure the path - - - forms cycle (notice that - - - is not cycle because you can' go from to
23,162
graphs figure graph with cycle cycle models the catch- situation (which some students claim to have actually encountered at certain institutions)in which course is prerequisite for course cc is prerequisite for dand is prerequisite for graph with no cycles is called tree the binary and multiway trees we saw earlier in this book are trees in this sense howeverthe trees that arise in graphs are more general than binary and multiway treeswhich have fixed maximum number of child nodes in grapha vertex in tree can be connected to any number of other verticesprovided that no cycles are created it' easy to figure out if non-directed graph has cycles if graph with nodes has more than - edgesit must have cycles you can make this clear to yourself by trying to draw graph with nodes and edges that does not have any cycles topological sort must be carried out on directed graph with no cycles such graph is called directed acyclic graphoften abbreviated dag java code here' the java code for the topo(methodwhich carries out the topological sortpublic void topo(int orig_nverts nverts/topological sort /remember how many verts while(nverts /while vertices remain/get vertex with no successorsor - int currentvertex nosuccessors()if(currentvertex =- /must be cycle system out println("errorgraph has cycles")return
23,163
/insert vertex label in sorted array (start at endsortedarray[nverts- vertexlist[currentvertexlabeldeletevertex(currentvertex)/end while /delete vertex /vertices all gonedisplay sortedarray system out print("topologically sorted order")for(int = <orig_nvertsj++system out printsortedarray[ )system out println("")/end topo the work is done in the while loopwhich continues until the number of vertices is reduced to here are the steps involved call nosuccessors(to find any vertex with no successors if such vertex is foundput the vertex label at the end of sortedarray[and delete the vertex from graph if an appropriate vertex isn' foundthe graph must have cycle the last vertex to be removed appears first on the listso the vertex label is placed in sortedarray starting at the end and working toward the beginningas nverts (the number of vertices in the graphgets smaller if vertices remain in the graph but all of them have successorsthe graph must have cycleand the algorithm displays message and quits if there are no cyclesthe while loop exitsand the list from sortedarray is displayedwith the vertices in topologically sorted order the nosuccessors(method uses the adjacency matrix to find vertex with no successors in the outer for loopit goes down the rowslooking at each vertex for each vertexit scans across the columns in the inner for looplooking for if it finds oneit knows that that vertex has successorbecause there' an edge from that vertex to another one when it finds it bails out of the inner loop so that the next vertex can be investigated only if an entire row is found with no do we know we have vertex with no successorsin this caseits row number is returned if no such vertex is found- is returned here' the nosuccessors(methodpublic int nosuccessors(/returns vert with no successors /(or - if no such verts
23,164
graphs boolean isedge/edge from row to column in adjmat for(int row= row<nvertsrow++/for each vertexisedge false/check edges for(int col= col<nvertscol++ifadjmat[row][col /if edge to /anotherisedge truebreak/this vertex /has successor /try another if!isedge /if no edgesreturn row/has no successors return - /no such vertex /end nosuccessors(deleting vertex is straightforward except for few details the vertex is removed from the vertexlist[arrayand the vertices above it are moved down to fill up the vacant position likewisethe row and column for the vertex are removed from the adjacency matrixand the rows and columns above and to the right are moved down and to the left to fill the vacancies these tasks are carried out by the deletevertex()moverowup()and movecolleft(methodswhich you can examine in the complete listing for topo java (listing it' actually more efficient to use the adjacency-list representation of the graph for this algorithmbut that would take us too far afield the main(routine in this program calls on methodssimilar to those we saw earlierto create the same graph shown in figure the addedge(methodas we notedinserts single number into the adjacency matrix because this is directed graph here' the code for main()public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/
23,165
thegraph addvertex(' ')thegraph addvertex(' ')/ / thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ad /ae /be /cf /dg /eg /fh /gh thegraph topo()/end main(/do the sort after the graph is createdmain(calls topo(to sort the graph and display the result here' the outputtopologically sorted orderbaedgcfh of courseyou can rewrite main(to generate other graphs the complete topo java program you've seen most of the routines in topo java already listing shows the complete program listing the topo java program /topo java /demonstrates topological sorting /to run this programc>java topoapp ///////////////////////////////////////////////////////////////class vertex public char label/label ( ' '/public vertex(char lab/constructor label lab/end class vertex ///////////////////////////////////////////////////////////////class graph private final int max_verts
23,166
listing graphs continued private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private char sortedarray[]/public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][ sortedarray new char[max_verts]/sorted vert labels /end constructor /public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endadjmat[start][end /public void displayvertex(int vsystem out print(vertexlist[vlabel)/public void topo(/topological sort int orig_nverts nverts/remember how many verts while(nverts /while vertices remain/get vertex with no successorsor - int currentvertex nosuccessors()if(currentvertex =- /must be cycle
23,167
listing continued system out println("errorgraph has cycles")return/insert vertex label in sorted array (start at endsortedarray[nverts- vertexlist[currentvertexlabeldeletevertex(currentvertex)/end while /delete vertex /vertices all gonedisplay sortedarray system out print("topologically sorted order")for(int = <orig_nvertsj++system out printsortedarray[ )system out println("")/end topo /public int nosuccessors(/returns vert with no successors /(or - if no such vertsboolean isedge/edge from row to column in adjmat for(int row= row<nvertsrow++/for each vertexisedge false/check edges for(int col= col<nvertscol++ifadjmat[row][col /if edge to /anotherisedge truebreak/this vertex /has successor /try another if!isedge /if no edgesreturn row/has no successors return - /no such vertex /end nosuccessors(/public void deletevertex(int delvertif(delvert !nverts- /if not last vertex
23,168
listing graphs continued /delete from vertexlist for(int =delvertj<nverts- ++vertexlist[jvertexlist[ + ]/delete row from adjmat for(int row=delvertrow<nverts- row++moverowup(rownverts)/delete col from adjmat for(int col=delvertcol<nverts- col++movecolleft(colnverts- )nverts--/one less vertex /end deletevertex /private void moverowup(int rowint lengthfor(int col= col<lengthcol++adjmat[row][coladjmat[row+ ][col]/private void movecolleft(int colint lengthfor(int row= row<lengthrow++adjmat[row][coladjmat[row][col+ ]//end class graph ///////////////////////////////////////////////////////////////class topoapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/
23,169
listing continued thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )thegraph addedge( )/ad /ae /be /cf /dg /eg /fh /gh thegraph topo()/do the sort /end main(/end class topoapp ///////////////////////////////////////////////////////////////in the next we'll see what happens when edges are given weight as well as direction connectivity in directed graphs we've seen how in non-directed graph you can find all the vertices that are connected by doing depth-first or breadth-first search when we try to find all the connected vertices in directed graphthings get more complicated you can' just start from randomly selected vertex and expect to reach all the other connected vertices consider the graph in figure if you start on ayou can get to but not to any of the other vertices if you start on byou can' get to dand if you start on cyou can' get anywhere the meaningful question about connectivity iswhat vertices can you reach if you start on particular vertexb figure directed graph
23,170
graphs the connectivity table you can easily modify the dfs java program (listing to start the search on each vertex in turn for the graph of figure the output will look something like thisac bace dec ec this is the connectivity table for the directed graph the first letter is the starting vertex and subsequent letters show the vertices that can be reached (either directly or via other verticesfrom the starting vertex warshall' algorithm in some applications it' important to find out quickly whether one vertex is reachable from another vertex perhaps you want to fly from athens to murmansk on hubris airlines and you don' care how many intermediate stops you need to make is this trip possibleyou could examine the connectivity tablebut then you would need to look through all the entries on given rowwhich would take (ntime (where is the average number of vertices reachable from given vertexbut you're in hurryis there faster wayit' possible to construct table that will tell you instantly (that isin ( timewhether one vertex is reachable from another such table can be obtained by systematically modifying graph' adjacency matrix the graph represented by this revised adjacency matrix is called the transitive closure of the original graph remember that in an ordinary adjacency matrix the row number indicates where an edge starts and the column number indicates where it ends (this is similar to the arrangement in the connectivity table at the intersection of row and column means there' an edge from vertex to vertex you can get from one vertex to the other in one step (of coursein directed graph it does not follow that you can go the other wayfrom to table shows the adjacency matrix for the graph of figure table adjacency matrix
23,171
table continued we can use warshall' algorithm to change the adjacency matrix into the transitive closure of the graph this algorithm does lot in few lines of code it' based on simple ideaif you can get from vertex to vertex mand you can get from to nthen you can get from to we've derived two-step path from two one-step paths the adjacency matrix shows all possible one-step pathsso it' good starting place to apply this rule you might wonder if this algorithm can find paths of more than two edges after allthe rule only talks about combining two one-edge paths into one two-edge path as it turns outthe algorithm will build on previously discovered multi-edge paths to create paths of arbitrary length the implementation we will describe guarantees this resultbut proof is beyond the scope of this book here' how it works we'll use table as an example we're going to examine every cell in the adjacency matrixone row at time row we start with row there' nothing in columns and bbut there' at column cso we stop there now the at this location says there is path from to if we knew there was path from some vertex to athen we would know there was path from to where are the edges (if anythat end at athey're in column so we examine all the cells in column in table there' only one in column aat row it says there' an edge from to so we know there' an edge from to aand another (the one we started withfrom to from this we infer that we can get from to in two steps you can verify this is true by looking at the graph in figure to record this resultwe put at the intersection of row and column the result is shown in figure the remaining cells of row are blank rows bcand we go to row the first cellat column ahas indicating an edge from to are there any edges that end at bwe look in column bbut it' emptyso we know that none of the we find in row will result in finding longer paths because no edges end at
23,172
graphs ay by to and to so to figure to and to so to steps in warshall' algorithm row has no at allso we go to row here we find an edge from to howevercolumn is emptyso there are no edges that end on row in row we see there' an edge from to looking in column we see the first entry is for the edge to eso with to and to we infer there' path from to howeverit' already been discoveredas indicated by the at that location there' another in column eat row this edge from to plus the one from to imply path from to cso we insert in that cell the result is shown in figure warshall' algorithm is now complete we've added two to the adjacency matrixwhich now shows which nodes are reachable from another node in any number of steps if we drew graph based on this new matrixit would be the transitive closure of the graph in figure implementation of warshall' algorithm one way to implement warshall' algorithm is with three nested loops (as suggested by sedgewicksee appendix "further reading"the outer loop looks at each rowlet' call its variable the loop inside that looks at each cell in the rowit uses variable if is found in cell (xy)there' an edge from to xand the third (innermostloop is activatedit uses variable the third loop examines the cells in column ylooking for an edge that ends at (note that is used for rows in the first loop but for the column in the third loop if there' in column at row zthen there' an edge from to with one edge from to and another from to xit follows that there' path from to xso you can put at (xzwe'll leave the details as an exercise
23,173
summary graphs consist of vertices connected by edges graphs can represent many real-world entitiesincluding airline routeselectrical circuitsand job scheduling search algorithms allow you to visit each vertex in graph in systematic way searches are the basis of several other activities the two main search algorithms are depth-first search (dfsand breadth-first search (bfsthe depth-first search algorithm can be based on stackthe breadth-first search algorithm can be based on queue minimum spanning tree (mstconsists of the minimum number of edges necessary to connect all graph' vertices slight modification of the depth-first search algorithm on an unweighted graph yields its minimum spanning tree in directed graphedges have direction (often indicated by an arrowa topological sorting algorithm creates list of vertices arranged so that vertex precedes vertex in the list if there' path from to topological sort can be carried out only on daga directed acyclic (no cyclesgraph topological sorting is typically used for scheduling complex projects that consist of tasks contingent on other tasks warshall' algorithm finds whether there is connectionof either one or multiple edgesfrom any vertex to any other vertex questions these questions are intended as self-test for readers answers may be found in appendix in graphan connects two how do you tellby looking at its adjacency matrixhow many edges there are in an undirected graph in game simulationwhat graph entity corresponds to choice about what move to make
23,174
graphs directed graph is one in which you must follow the minimum spanning tree you must go from vertex to vertex to vertex and so on you can go in only one direction from one given vertex to another you can go in only one direction on any given path if an adjacency matrix has rows { , , , }{ , , , }{ , , , }and { , , , }what is the corresponding adjacency list minimum spanning tree is graph in which the number of edges connecting all the vertices is as small as possible the number of edges is equal to the number of vertices all unnecessary vertices have been removed every combination of two vertices is connected by the minimum number of edges how many different minimum spanning trees are there in an undirected graph of three vertices and three edges an undirected graph must have cycle if any vertex can be reached from some other vertex the number of paths is greater than the number of vertices the number of edges is equal to the number of vertices the number of paths is less than the number of edges is graph with no cycles can minimum spanning tree for an undirected graph have cycles true or falsethere may be many correct topological sorts for given graph topological sorting results in vertices arranged so the directed edges all go in the same direction vertices listed in order of increasing number of edges from the beginning vertex vertices arranged so precedes bwhich precedes cand so on vertices listed so the ones later in the list are downstream from the ones earlier
23,175
what' dag can tree have cycles what evidence does the topo java program (listing use to deduce that graph has cycleexperiments carrying out these experiments will help to provide insights into the topics covered in the no programming is involved using the graphn workshop appletdraw graph with five vertices and seven edges thenwithout using the view buttonwrite down the adjacency matrix for the graph when you're donepush the view button to see if you got it right normal tic-tac-toe game is played on boardbut for simplicitythink of tic-tac-toe gamein which player needs only xs or os to win use the graphn applet to create graph corresponding to such game do you really need depth of create five-vertex adjacency matrix and insert and randomly don' worry about symmetry nowwithout using the view buttoncreate the corresponding directed graph using the graphd workshop applet when you're donepush the view button to see if the graph corresponds to your adjacency matrix in the graphd workshop appletsee if you can create graph with cycle that the topo routine cannot identify programming projects writing programs to solve the programming projects helps to solidify your understanding of the material and demonstrates how the concepts are applied (as noted in the introductionqualified instructors may obtain completed solutions to the programming projects on the publisher' web site modify the bfs java program (listing to find the minimum spanning tree using breadth-first searchrather than the depth-first search shown in mst java (listing in main()create graph with vertices and edgesand find its minimum spanning tree modify the dfs java program (listing to use adjacency lists rather than an adjacency matrix you can obtain list by adapting the link and linklist classes from the linklist java program (listing in modify the
23,176
graphs find(routine from linklist to search for an unvisited vertex rather than for key value modify the dfs java program (listing to display connectivity table for directed graphas described in the section "connectivity in directed graphs implement warshall' algorithm to find the transitive closure for graph you could start with the code from programming project it' useful to be able to display the adjacency matrix at various stages of the algorithm' operation the knight' tour is an ancient and famous chess puzzle the object is to move knight from one square to another on an otherwise empty chess board until it has visited every square exactly once write program that solves this puzzle using depth-first search it' best to make the board size variable so that you can attempt solutions for smaller boards the regular board can take years to solve on desktop computerbut board takes only minute or so refer to the section "depth-first search and game simulationsin this it may be easier to think of new knight being created and remaining on the new square when move is made this waya knight corresponds to vertexand sequence of knights can be pushed onto the stack when the board is completely filled with knights (the stack is full)you win in this problem the board is traditionally numbered sequentiallyfrom at the upper-left corner to at the lower-right corner (or to on boardwhen looking for its next movea knight must not only make legal knight' moveit must also not move off the board or onto an already-occupied (visitedsquare if you make the program display the board and wait for keypress after every moveyou can watch the progress of the algorithm as it places more and more knights on the boardand thenwhen it gets boxed inbacktracks by removing some knights and trying different series of moves we'll have more to say about the complexity of this problem in the next
23,177
weighted graphs in this minimum spanning tree with weighted graphs the shortest-path problem in the preceding we saw that graph' edges can have direction in this we'll explore another edge featureweight for exampleif vertices in weighted graph represent citiesthe weight of the edges might represent distances between the citiesor costs to fly between themor the number of automobile trips made annually between them ( figure of interest to highway engineerswhen we include weight as feature of graph' edgessome interesting and complex questions arise what is the minimum spanning tree for weighted graphwhat is the shortest (or cheapestdistance from one vertex to anothersuch questions have important applications in the real world we'll first examine weighted but non-directed graph and its minimum spanning tree in the second half of this we'll examine graphs that are both directed and weightedin connection with the famous dijkstra' algorithmused to find the shortest path from one vertex to another minimum spanning tree with weighted graphs to introduce weighted graphswe'll return to the question of the minimum spanning tree creating such tree is bit more complicated with weighted graph than with an unweighted one when all edges are the same weightit' fairly straightforward--as we saw in "graphs"--for the algorithm to choose one to add to the minimum spanning tree but when edges can have different weightssome arithmetic is needed to choose the right one the all-pairs shortest-path problem efficiency intractable problems
23,178
weighted graphs an examplecable tv in the jungle suppose we want to install cable television line that connects six towns in the mythical country of magnaguena five links will connect the six citiesbut which five links should they bethe cost of connecting each pair of cities variesso we must pick the route carefully to minimize the overall cost figure shows weighted graph with six verticesrepresenting the towns ajobordocolinadanzaerizoand flor each edge has weightshown by number alongside the edge imagine that these numbers represent the costin millions of magnaguenian dollarsof installing cable link between two cities (notice that some links are impractical because of distance or terrainfor examplewe will assume that it' too far from ajo to colina or from danza to florso these links don' need to be considered and don' appear on the graph bordo colina ajo flor danza figure erizo weighted graph how can we pick route that minimizes the cost of installing the cable systemthe answer is to calculate minimum spanning tree it will have five links (one fewer than the number of towns)it will connect all six townsand it will minimize the total cost of building these links can you figure out this route by looking at the graph in figure if notyou can solve the problem with the graphw workshop applet the graphw workshop applet the graphw workshop applet is similar to graphn and graphdbut it creates weightedundirected graphs before you drag from vertex to vertex to create an edgeyou must type the weight of the edge into the text box in the upper-right corner this applet carries out only one algorithmwhen you repeatedly click the tree buttonit finds the minimum spanning tree for whatever graph you have created the new and view buttons work as in previous graph applets to erase an old graph and to view the adjacency matrix
23,179
try out this applet by creating some small graphs and finding their minimum spanning trees (for some configurations you'll need to be careful positioning the vertices so that the weight numbers don' fall on top of each other as you step through the algorithmyou'll see that vertices acquire red borders and edges are made thicker when they're added to the minimum spanning tree vertices that are in the tree are also listed below the graphon the left on the rightthe contents of priority queue (pqare shown the items in the priority queue are edges for instancethe entry ab in the queue is the edge from to bwhich has weight of we'll explain what the priority queue does after we've shown an example of the algorithm use the graphw workshop applet to construct the graph of figure the result should resemble figure figure the graphw workshop applet now find this graph' minimum spanning tree by stepping through the algorithm with the tree button the result should be the minimum spanning tree shown in figure the applet should discover that the minimum spanning tree consists of the edges adabbeecand cffor total edge weight of the order in which the edges are specified is unimportant if you start at different vertexyou will create tree with the same edgesbut in different order
23,180
weighted graphs bordo colina ajo flor figure danza erizo the minimum spanning tree send out the surveyors the algorithm for constructing the minimum spanning tree is little involvedso we're going to introduce it using an analogy involving cable tv employees you are one employee-- managerof course--and there are also various surveyors computer algorithm (unless perhaps it' neural networkdoesn' "knowabout all the data in given problem at onceit can' deal with the big picture it must acquire the data little by littlemodifying its view of things as it goes along with graphsalgorithms tend to start at some vertex and work outwardacquiring data about nearby vertices before finding out about vertices farther away we saw examples of this in the depth-first and breadth-first searches in the preceding in similar waywe're going to assume that you don' start out knowing the costs of installing the cable tv line between all the pairs of towns in magnaguena acquiring this information takes time that' where the surveyors come in starting in ajo you start by setting up an office in ajo (you could start in any townbut ajo has the best restaurants only two towns are reachable from ajobordo and danza (see figure you hire two toughjungle-savvy surveyors and send them out along the dangerous wilderness trailsone to bordo and one to danza their job is to determine the cost of installing cable along these routes the first surveyor arrives in bordohaving completed her surveyand calls you on her cell phoneshe says it will cost million dollars to install the cable link between ajo and bordo the second surveyorwho has had some trouble with crocodilesreports little later from danza that the ajo-danza linkwhich crosses more level countrywill cost only million dollars you make listajo-danza$ million ajo-bordo$ million
23,181
you always list the links in order of increasing costwe'll see why this is good idea soon building the ajo-danza link at this point you figure you can send out the construction crew to actually install the cable from ajo to danza how can you be sure the ajo-danza route will eventually be part of the cheapest solution (the minimum spanning tree)so faryou know the cost of only two links in the system don' you need more informationto get feel for this situationtry to imagine some other route linking ajo to danza that would be cheaper than the direct link if it doesn' go directly to danzathis other route must go through bordo and circle back to danzapossibly via one or more other towns but you already know the link to bordo is more expensiveat million dollarsthan the link to danzaat so even if the remaining links in this hypothetical circle route are cheapas shown in figure it will still be more expensive to get to danza by going through bordo alsoit will be more expensive to get to towns on the circle routelike xby going through bordo than by going through danza hypothetical circle route bordo ajo danza known figure unknown hypothetical circle route we conclude that the ajo-danza route will be part of the minimum spanning tree this isn' formal proof (which is beyond the scope of this book)but it does suggest your best bet is to pick the cheapest link so you build the ajo-danza link and install an office in danza why do you need an officedue to magnaguena government regulationyou must install an office in town before you can send out surveyors from that town to adjacent towns in graph termsyou must add vertex to the tree before you can learn the weight of the edges leading away from that vertex all towns with offices are connected by cable with each othertowns with no offices are not yet connected
23,182
weighted graphs building the ajo-bordo link after you've completed the ajo-danza link and built your office in danzayou can send out surveyors from danza to all the towns reachable from there these are bordocolinaand erizo the surveyors reach their destinations and report back costs of and million dollarsrespectively (of courseyou don' send surveyor to ajo because you've already surveyed the ajo-danza route and installed its cable now you know the costs of four links from towns with offices to towns with no officesajo-bordo$ million danza-bordo$ million danza-colina$ million danza-erizo$ million why isn' the ajo-danza link still on the listbecause you've already installed the cable therethere' no point giving any further consideration to this link the route on which cable has just been installed is always removed from the list at this point it may not be obvious what to do next there are many potential links to choose from what do you imagine is the best strategy nowhere' the rulerule from the listalways pick the cheapest edge actuallyyou already followed this rule when you chose which route to follow from ajothe ajo-danza edge was the cheapest here the cheapest edge is ajo-bordoso you install cable link from ajo to bordo for cost of million dollarsand build an office in bordo let' pause for moment and make general observation at given time in the cable system constructionthere are three kinds of towns towns that have offices and are linked by cable (in graph terms they're in the minimum spanning tree towns that aren' linked yet and have no officebut for which you know the cost to link them to at least one town with an office we can call these "fringetowns towns you don' know anything about
23,183
at this stageajodanzaand bordo are in category colina and erizo are in category and flor is in category as shown in figure as we work our way through the algorithmtowns move from category to and from to bordo colina ajo flor danza towns with offices (vertices in the treefigure erizo fringe towns (not in the treeunknown towns (not in the treepartway through the minimum spanning tree algorithm building the bordo-erizo link at this pointajodanzaand bordo are connected to the cable system and have offices you already know the costs from ajo and danza to towns in category but you don' know these costs from bordo so from bordo you send out surveyors to colina and erizo they report back costs of million dollars to colina and to erizo here' the new listbordo-erizo$ million danza-colina$ million bordo-colina$ million danza-erizo$ million the danza-bordo link was on the previous list but is not on this one becauseas we notedthere' no point in considering links to towns that are already connectedeven by an indirect route from this list we can see that the cheapest route is bordo-erizoat million dollars you send out the crew to install this cable linkand you build an office in erizo (see figure
23,184
weighted graphs building the erizo-colina link from erizo the surveyors report back costs of million dollars to colina and to flor the danza-erizo link from the previous list must be removed because erizo is now connected town your new list is erizo-colina$ million erizo-flor$ million danza-colina$ million bordo-colina$ million the cheapest of these links is erizo-colinaso you build this link and install an office in colina andfinallythe colina-flor link the choices are narrowing after you remove already-linked townsyour list now shows only colina-flor$ million erizo-flor$ million you install the last link of cable from colina to florbuild an office in florand you're done you know you're done because there' now an office in every town you've constructed the cable route ajo-danzaajo-bordobordo-erizoerizo-colinaand colina-floras shown earlier in figure this is the cheapest possible route linking the six towns of magnaguena creating the algorithm using the somewhat fanciful idea of installing cable tv systemwe've shown the main ideas behind the minimum spanning tree for weighted graphs now let' see how we' go about creating the algorithm for this process the priority queue the key activity in carrying out the algorithmas described in the cable tv examplewas maintaining list of the costs of links between pairs of cities we decided where to build the next link by selecting the minimum of these costs list in which we repeatedly select the minimum value suggests priority queue as an appropriate data structureand in fact this turns out to be an efficient way to handle the minimum spanning tree problem instead of list or arraywe use
23,185
priority queue in serious program this priority queue might be based on heapas described in "heaps this would speed up operations on large priority queues howeverin our demonstration program we'll use priority queue based on simple array outline of the algorithm let' restate the algorithm in graph terms (as opposed to cable tv terms)start with vertexand put it in the tree then repeatedly do the following find all the edges from the newest vertex to other vertices that aren' in the tree put these edges in the priority queue pick the edge with the lowest weightand add this edge and its destination vertex to the tree repeat these steps until all the vertices are in the tree at that pointyou're done in step newest means most recently installed in the tree the edges for this step can be found in the adjacency matrix after step the list will contain all the edges from vertices in the tree to vertices on the fringe extraneous edges in maintaining the list of linkswe went to some trouble to remove links that led to town that had recently become connected if we didn' do thiswe would have ended up installing unnecessary cable links in programming algorithm we must likewise make sure that we don' have any edges in the priority queue that lead to vertices that are already in the tree we could go through the queue looking for and removing any such edges each time we added new vertex to the tree as it turns outit is easier to keep only one edge from the tree to given fringe vertex in the priority queue at any given time that isthe queue should contain only one edge to each category vertex you'll see that this is what happens in the graphw workshop applet there are fewer edges in the priority queue than you might expect--just one entry for each category vertex step through the minimum spanning tree for figure and verify that this is what happens table shows how edges with duplicate destinations have been removed from the priority queue
23,186
weighted graphs table edge pruning step number list unpruned edge list pruned edge (in priority queueduplicate removed from priority queue ab ad de dc db ab de bc dc be bc dc ef ec ef cf ab ad de dc ab dc be ef ec cf db (ab de (be )bc (dc bc (ec )dc (ec ef remember that an edge consists of letter for the source (startingvertex of the edgea letter for the destination (ending vertex)and number for the weight the second column in this table corresponds to the lists you kept when constructing the cable tv system it shows all edges from category vertices (those in the treeto category vertices (those with at least one known edge from category vertexthe third column is what you see in the priority queue when you run the graphw applet any edge with the same destination vertex as another edgeand which has greater weighthas been removed the fourth column shows the edges that have been removed andin parenthesesthe edge with the smaller weight that superseded it and remains in the queue remember that as you go from step to step the last entry on the list is always removed because this edge is added to the tree looking for duplicates in the priority queue how do we make sure there is only one edge per category vertexeach time we add an edge to the queuewe make sure there' no other edge going to the same destination if there iswe keep only the one with the smallest weight this necessitates looking through the priority queue item by itemto see if there' such duplicate edge priority queues are not designed for random accessso this is not an efficient activity howeverviolating the spirit of the priority queue is necessary in this situation java code the method that creates the minimum spanning tree for weighted graphmstw()follows the algorithm outlined earlier as in our other graph programsit assumes there' list of vertices in vertexlist[]and that it will start with the vertex at index the currentvert variable represents the vertex most recently added to the tree here' the code for mstw()
23,187
public void mstw(currentvert /minimum spanning tree /start at while(ntree nverts- /while not all verts in tree /put currentvert in tree vertexlist[currentvertisintree truentree++/insert edges adjacent to currentvert into pq for(int = <nvertsj++/for each vertexif( ==currentvert/skip if it' us continueif(vertexlist[jisintree/skip if in the tree continueint distance adjmat[currentvert][ ]ifdistance =infinity/skip if no edge continueputinpq(jdistance)/put it in pq (maybeif(thepq size()== /no vertices in pqsystem out println(graph not connected")return/remove edge with minimum distancefrom pq edge theedge thepq removemin()int sourcevert theedge srcvertcurrentvert theedge destvert/display edge from source to current system out printvertexlist[sourcevertlabel )system out printvertexlist[currentvertlabel )system out print(")/end while(not all verts in tree/mst is complete for(int = <nvertsj++/unmark vertices vertexlist[jisintree false/end mstw(
23,188
weighted graphs the algorithm is carried out in the while loopwhich terminates when all vertices are in the tree within this loop the following activities take place the current vertex is placed in the tree the edges adjacent to this vertex are placed in the priority queue (if appropriate the edge with the minimum weight is removed from the priority queue the destination vertex of this edge becomes the current vertex let' look at these steps in more detail in step the currentvert is placed in the tree by marking its isintree field in step the edges adjacent to this vertex are considered for insertion in the priority queue the edges are examined by scanning across the row whose number is currentvert in the adjacency matrix an edge is placed in the queue unless one of these conditions is truethe source and destination vertices are the same the destination vertex is in the tree there is no edge to this destination if none of these conditions are truethe putinpq(method is called to put the edge in the priority queue actuallythis routine doesn' always put the edge in the queue eitheras we'll see in moment in step the edge with the minimum weight is removed from the priority queue this edge and its destination vertex are added to the treeand the source vertex (currentvertand destination vertex are displayed at the end of mstw()the vertices are removed from the tree by resetting their isintree variables that isn' strictly necessary in this program because only one tree is created from the data howeverit' good housekeeping to restore the data to its original form when you finish with it as we notedthe priority queue should contain only one edge with given destination vertex the putinpq(method makes sure this is true it calls the find(method of the priorityq classwhich has been doctored to find the edge with specified destination vertex if there is no such vertexand find(therefore returns - then putinpq(simply inserts the edge into the priority queue howeverif such an edge does existputinpq(checks to see whether the existing edge or the new proposed edge has the lower weight if it' the old edgeno change is necessary if the new one has lower weightthe old edge is removed from the queue and the new one is installed here' the code for putinpq()
23,189
public void putinpq(int newvertint newdist/is there another edge with the same destination vertexint queueindex thepq find(newvert)/got edge' index if(queueindex !- /if there is one/get edge edge tempedge thepq peekn(queueindex)int olddist tempedge distanceif(olddist newdist/if new edge shorterthepq removen(queueindex)/remove old edge edge theedge new edge(currentvertnewvertnewdist)thepq insert(theedge)/insert new edge /else no actionjust leave the old vertex there /end if else /no edge with same destination vertex /so insert new one edge theedge new edge(currentvertnewvertnewdist)thepq insert(theedge)/end putinpq(the mstw java program the priorityq class uses an array to hold the members as we notedin program dealing with large graphsa heap would be more appropriate than the array shown here the priorityq class has been augmented with various methods it canas we've seenfind an edge with given destination vertex with find(it can also peek at an arbitrary member with peekn()and remove an arbitrary member with removen(most of the rest of this program you've seen before listing shows the complete mstw java program listing the mstw java program /mstw java /demonstrates minimum spanning tree with weighted graphs /to run this programc>java mstwapp ///////////////////////////////////////////////////////////////class edge public int srcvert/index of vertex starting edge public int destvert/index of vertex ending edge
23,190
weighted graphs listing continued public int distance/distance from src to dest /public edge(int svint dvint /constructor srcvert svdestvert dvdistance //end class edge ///////////////////////////////////////////////////////////////class priorityq /array in sorted orderfrom max at to min at size- private final int size private edge[quearrayprivate int size/public priorityq(/constructor quearray new edge[size]size /public void insert(edge item/insert item in sorted order int jfor( = <sizej++/find place to insert ifitem distance >quearray[jdistance breakfor(int =size- >=jk--/move items up quearray[ + quearray[ ]quearray[jitem/insert item size++/public edge removemin(/remove minimum item return quearray[--size]
23,191
listing continued /public void removen(int /remove item at for(int =nj<size- ++/move items down quearray[jquearray[ + ]size--/public edge peekmin(/peek at minimum item return quearray[size- ]/public int size(/return number of items return size/public boolean isempty(/true if queue is empty return (size== )/public edge peekn(int /peek at item return quearray[ ]/public int find(int finddex/find item with specified /destvert value for(int = <sizej++if(quearray[jdestvert =finddexreturn jreturn - //end class priorityq ///////////////////////////////////////////////////////////////class vertex public char label/label ( ' 'public boolean isintree/public vertex(char lab/constructor label labisintree false/
23,192
weighted graphs listing continued /end class vertex ///////////////////////////////////////////////////////////////class graph private final int max_verts private final int infinity private vertex vertexlist[]/list of vertices private int adjmat[][]/adjacency matrix private int nverts/current number of vertices private int currentvertprivate priorityq thepqprivate int ntree/number of verts in tree /public graph(/constructor vertexlist new vertex[max_verts]/adjacency matrix adjmat new int[max_verts][max_verts]nverts for(int = <max_vertsj++/set adjacency for(int = <max_vertsk++/matrix to adjmat[ ][kinfinitythepq new priorityq()/end constructor /public void addvertex(char labvertexlist[nverts++new vertex(lab)/public void addedge(int startint endint weightadjmat[start][endweightadjmat[end][startweight/public void displayvertex(int vsystem out print(vertexlist[vlabel)/
23,193
listing continued public void mstw(currentvert /minimum spanning tree /start at while(ntree nverts- /while not all verts in tree /put currentvert in tree vertexlist[currentvertisintree truentree++/insert edges adjacent to currentvert into pq for(int = <nvertsj++/for each vertexif( ==currentvert/skip if it' us continueif(vertexlist[jisintree/skip if in the tree continueint distance adjmat[currentvert][ ]ifdistance =infinity/skip if no edge continueputinpq(jdistance)/put it in pq (maybeif(thepq size()== /no vertices in pqsystem out println(graph not connected")return/remove edge with minimum distancefrom pq edge theedge thepq removemin()int sourcevert theedge srcvertcurrentvert theedge destvert/display edge from source to current system out printvertexlist[sourcevertlabel )system out printvertexlist[currentvertlabel )system out print(")/end while(not all verts in tree/mst is complete for(int = <nvertsj++/unmark vertices vertexlist[jisintree false/end mstw
23,194
weighted graphs listing continued /public void putinpq(int newvertint newdist/is there another edge with the same destination vertexint queueindex thepq find(newvert)if(queueindex !- /got edge' index edge tempedge thepq peekn(queueindex)/get edge int olddist tempedge distanceif(olddist newdist/if new edge shorterthepq removen(queueindex)/remove old edge edge theedge new edge(currentvertnewvertnewdist)thepq insert(theedge)/insert new edge /else no actionjust leave the old vertex there /end if else /no edge with same destination vertex /so insert new one edge theedge new edge(currentvertnewvertnewdist)thepq insert(theedge)/end putinpq(//end class graph ///////////////////////////////////////////////////////////////class mstwapp public static void main(string[argsgraph thegraph new graph()thegraph addvertex(' ')/ (start for mstthegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addvertex(' ')/ thegraph addedge( )thegraph addedge( )/ab /ad
23,195
listing continued thegraph addedge( )/bc thegraph addedge( )/bd thegraph addedge( )/be thegraph addedge( )/cd thegraph addedge( )/ce thegraph addedge( )/cf thegraph addedge( )/de thegraph addedge( )/ef system out print("minimum spanning tree")thegraph mstw()/minimum spanning tree system out println()/end main(/end class mstwapp //////////////////////////////////////////////////////////////the main(routine in class mstwapp creates the tree in figure here' the outputminimum spanning treead ab be ec cf the shortest-path problem perhaps the most commonly encountered problem associated with weighted graphs is that of finding the shortest path between two given vertices the solution to this problem is applicable to wide variety of real-world situationsfrom the layout of printed circuit boards to project scheduling it is more complex problem than we've seen beforeso let' start by looking at (somewhatreal-world scenario in the same mythical country of magnaguena introduced in the preceding section the railroad line this time we're concerned with railroads rather than cable tv howeverthis project is not as ambitious as the last one we're not going to build the railroadit already exists we just want to find the cheapest route from one city to another the railroad charges passengers fixed fare to travel between any two towns these fares are shown in figure that isthe fare from ajo to bordo is $ from bordo to danza is $ and so on these rates are the same whether the ride between two towns is part of longer itinerary or not (unlike the situation with today' airline fares
23,196
weighted graphs bordo colina $ $ $ ajo $ $ $ $ danza figure $ erizo train fares in magnaguena the edges in figure are directed they represent single-track railroad lineson which (in the interest of safetytravel is permitted in only one direction for exampleyou can go directly from ajo to bordobut not from bordo to ajo although in this situation we're interested in the cheapest faresthe graph problem is nevertheless always referred to as the shortest-path problem (spphere shortest doesn' necessarily mean shortest in terms of distanceit can also mean cheapestfastestor best route by some other measure cheapest fares there are several possible routes between any two towns for exampleto take the train from ajo to erizoyou could go through danzaor you could go through bordo and colinaor through danza and colinaor you could take several other routes (it' not possible to reach the town of flor by rail because it lies beyond the rugged sierra descaro rangeso it doesn' appear on the graph this is fortunatebecause it reduces the size of certain lists we'll need to make the shortest-path problem is thisfor given starting point and destinationwhat' the cheapest routein figure you can see (with little mental effortthat the cheapest route from ajo to erizo passes through danza and colinait will cost you $ directedweighted graph as we notedour railroad has only single-track linesso you can go in only one direction between any two cities this corresponds to directed graph we could have portrayed the more realistic situation in which you can go either way between two cities for the same pricethis would correspond to non-directed graph howeverthe shortest-path problem is similar in these casesso for variety we'll show how it looks in directed graph
23,197
dijkstra' algorithm the solution we'll show for the shortest-path problem is called dijkstra' algorithmafter edsger dijkstrawho first described it in this algorithm is based on the adjacency matrix representation of graph somewhat surprisinglyit finds not only the shortest path from one specified vertex to anotherbut also the shortest paths from the specified vertex to all the other vertices agents and train rides to see how dijkstra' algorithm worksimagine that you want to find the cheapest way to travel from ajo to all the other towns in magnaguena you (and various agents you will hireare going to play the role of the computer program carrying out dijkstra' algorithm of coursein real life you could probably obtain schedule from the railroad with all the fares the algorithmhowevermust look at one piece of information at timeso (as in the preceding sectionwe'll assume that you are similarly unable to see the big picture at each townthe stationmaster can tell you how much it will cost to travel to the other towns that you can reach directly (that isin single ridewithout passing through another townalashe cannot tell you the fares to towns further than one ride away you keep notebookwith column for each town you hope to end up with each column showing the cheapest route from your starting point to that town the first agentin ajo eventuallyyou're going to place an agent in every townthis agent' job is to obtain information about ticket costs to other towns you yourself are the agent in ajo all the stationmaster in ajo can tell you is that it will cost $ to ride to bordo and $ to ride to danza you write this information in your notebookas shown in table table step an agent at ajo from ajo tobordo colina danza erizo step (via ajoinf (via ajoinf the entry "infis short for "infinity,and means that you can' get from ajo to the town shown in the column heador at least that you don' yet know how to get there (in the algorithm infinity will be represented by very large numberwhich will help with calculationsas we'll see the table entries in parentheses show the last town visited before you arrive at the various destinations we'll see later why this is good to know what do you do nowhere' the rule you'll followrule always send an agent to the town whose overall fare from the starting point (ajois the cheapest
23,198
weighted graphs you don' consider towns that already have an agent notice that this is not the same rule as that used in the minimum spanning tree problem (the cable tv installationthereyou picked the least expensive single link (edgefrom the connected towns to an unconnected town hereyou pick the least expensive total route from ajo to town with no agent in this particular point in your investigation these two approaches amount to the same thingbecause all known routes from ajo consist of only one edgebut as you send agents to more townsthe routes from ajo will become the sum of several direct edges the second agentin bordo the cheapest fare from ajo is to bordoat $ so you hire passerby and send him to bordowhere he'll be your agent when he' therehe calls you by telephone and tells you that the bordo stationmaster says it costs $ to ride to colina and $ to danza doing some quick arithmeticyou figure it must be $ plus $ or $ to go from ajo to colina via bordoso you modify the entry for colina you also can see thatgoing via bordoit must be $ plus $ or $ from ajo to danza however--and this is key point--you already know it' only $ going directly from ajo to danza you care only about the cheapest route from ajoso you ignore the more expensive routeleaving this entry as it was the resulting notebook entries are shown as the last row in table figure shows the situation geographically $ $ bordo $ colina $ ajo $ towns with agents (vertices in treefigure danza fringe towns (not in treee erizo unknown towns (not in treefollowing step in the shortest-path algorithm
23,199
table step agents at ajo and bordo from ajo tobordo colina danza erizo step step (via ajo (via ajo)inf (via bordo (via ajo (via ajoinf inf after we've installed an agent in townwe can be sure that the route taken by the agent to get to that town is the cheapest route whyconsider the present case if there were cheaper route than the direct one from ajo to bordoit would need to go through some other town but the only other way out of ajo is to danzaand that ride is already more expensive than the direct route to bordo adding additional fares to get from danza to bordo would make the danza route still more expensive from this we decide that from now on we won' need to update the entry for the cheapest fare from ajo to bordo this fare will not changeno matter what we find out about other towns we'll put next to it to show that there' an agent in the town and that the cheapest fare to it is fixed three kinds of towns as in the minimum spanning tree algorithmwe're dividing the towns into three categories towns in which we've installed an agentthey're in the tree towns with known fares from towns with an agentthey're on the fringe unknown towns at this point ajo and bordo are category towns because they have agents there category towns form tree consisting of paths that all begin at the starting vertex and that each end on different destination vertex (this is not the same treeof courseas minimum spanning tree some other towns have no agentsbut you know the fares to them because you have agents in adjacent category towns you know the fare from ajo to danza is $ and from bordo to colina is $ because the fares to them are knowndanza and colina are category (fringetowns you don' know anything yet about erizoit' an "unknowntown figure shows these categories at the current point in the algorithm as in the minimum spanning tree algorithmthis algorithm moves towns from the unknown category to the fringe categoryand from the fringe category to the treeas it goes along