// Chap 6, pp 289 - 290 boolean IsPath(int OriginCity, int DestCity, mapClass M) // ----------------------------------------------------- // Determines whether a sequence of flights between two // cities exists. Nonrecursive stack version. // Precondition: OriginCity and DestCity are the city // numbers of the origin and destination cities, // respectively. M is the flight map. // Postcondition: Returns TRUE if a sequence of flights // exists from OriginCity to DestCity, otherwise returns // FALSE. Arguments are unchanged. // Calls: Stack operations, UnvisitAll, MarkVisited, // and GetNextCity. // Implementation note: Uses a stack S for the city // numbers of a potential path. // ----------------------------------------------------- { stackClass S; int TopCity, NextCity; boolean Success; M.UnvisitAll(); // clear marks on all cities // push origin city onto stack, mark it visited S.Push(OriginCity, Success); M.MarkVisited(OriginCity); S.GetStackTop(TopCity, Success); while ( !S.StackIsEmpty() && (TopCity != DestCity) ) { // loop invariant: stack S contains a directed path // from the origin city at the bottom of S to the // city at the top of S // find an unvisited city adjacent to the city on the // top of the stack M.GetNextCity(TopCity, NextCity, Success); if (!Success) S.Pop(Success); // no city found; backtrack else // visit city { S.Push(NextCity, Success); M.MarkVisited(NextCity); } // end if S.GetStackTop(TopCity, Success); } // end while if (S.StackIsEmpty()) return FALSE; // no path exists else return TRUE; // path exists } // end IsPath