bool mapClass::IsPath(int OriginCity, int DestinationCity) // ----------------------------------------------------- // Determines whether a sequence of flights between two // cities exists. Nonrecursive stack version. // Precondition: OriginCity and DestinationCity are the city // numbers of the origin and destination cities, // respectively. // Postcondition: Returns true if a sequence of flights // exists from OriginCity to DestinationCity, otherwise // returns false. Cities visited during the search are // marked as visited in the flight map. // Implementation notes: Uses a stack S for the city // numbers of a potential path. Calls UnvisitAll, // MarkVisited, and GetNextCity. // ----------------------------------------------------- { stackClass S; int TopCity, NextCity; bool Success; UnvisitAll(); // clear marks on all cities // push origin city onto stack, mark it visited S.Push(OriginCity, Success); MarkVisited(OriginCity); S.GetStackTop(TopCity, Success); while (!S.StackIsEmpty() && (TopCity != DestinationCity)) { // 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 GetNextCity(TopCity, NextCity, Success); if (!Success) S.Pop(Success); // no city found; backtrack else // visit city { S.Push(NextCity, Success); 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