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[indexto...
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 u...
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 ...
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...
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 r...
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...
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 is...
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...
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 ...
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 t...
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 rem...
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 / applicati...
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 trickled...
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 arra...
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 so...
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(heaparra...
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 pr...
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()...
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 in...
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 ( *logntim...
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 sor...
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 remo...
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 wr...
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 d...
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 grap...
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 app...
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...
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 ...
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...
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...
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 ...
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(vertexl...
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 ...
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 ...
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 l...
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 algo...
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 ...
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 ...
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 th...
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 //////////////////////...
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 ...
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 p...
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 n...
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 mo...
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 alo...
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 fr...
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 ...
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 lis...
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 f...
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 displ...
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 v...
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...
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 appropri...
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(...
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 bool...
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 ...
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 ...
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")thegra...
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 h...
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 instea...
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 p...
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 bt...
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 ...
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 to...
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 ver...
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 sor...
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_ver...
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_n...
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 ...
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 /////////////////////////////////////////////////////////////...
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...
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-ste...
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 w...
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 a...
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 { , , ...
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 ed...
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...
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 th...
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...
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 mad...
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 va...
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 (...
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 (...
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...
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...
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 ...
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 (starti...
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[jisin...
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 weig...
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)...
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...
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 ...
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...
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 continuei...
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 ...
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 clas...
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 ...
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 a...
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...
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 r...