[an error occurred while processing this directive]
An invariant is a statement placed in a code segment that should be true each time the the loop execution reaches that point. Invariants are often used in a loops and recursions. In object-oriented programming, invariants can refer to the state of an object, and they should be true at all times except during the execution of methods for the object.
If an invariant is placed at the beginning of a while or do..while loop whose condition test does not change the state of the computation (that is, it has no side effects), then the invariant should also be true at the bottom of the loop.
If the loop satisfies the above checks then the postcondition must be true whenever the precondition is true, provided that the loop terminates. Since it it possible for a loop to run forever, one more check is needed:
visit v
put all of the edges that leave v into the dispenser
-- Preconditions:
-- v is visited. Every other vertex in the graph is unvisited.
-- Every edge in the graph that goes from v to another vertex
-- is in the dispenser.
while the dispenser is not empty
-- Invariant:
-- Every edge in the graph that goes from a visited
-- vertex to an unvisited vertex is in the dispenser.
retrieve and remove edge e from the dispenser
let w be the head of e
if w has not been visited
visit e
visit w
put all of the edges that leave w into the dispenser
endif
endwhile
-- Postcondition:
-- There are no edges in the graph that go from a
-- visited vertex to an unvisited vertex.
For the graph search loop, the truth of the invariant can be changed in two ways: an edge can be added or removed from the dispenser, or the visited status of its end vertices can be changed. There are two cases to consider, depending on the truth of the if statement condition.
If the head of e has not been visited then the removal of e from the dispenser can falsify the invariant. But then later code changes the status of its head vertex so that at the end of the loop the removed edge does not go from a visited vertex to an unvisited vertex. Changing the status of the head vertex to visited also can make more edges that go from visited vertices to unvisited vertices, but all edges that leave the head of e are added to the dispenser, so the invariant is not falsified in the end.
If the head of e has been visited then its removal does not falsify the invariant. And in this case, the visited status of vertices is unchanged, so the invariant remains true.
In the graph search algorithm, the precondition is guaranteed by the code preceding the loop, so the postcondition is always ensured.
This conclusion could have been used as the postcondition. In fact, it is a better postcondition because it addresses the purpose of the graph search more directly.
[an error occurred while processing this directive]