reachableFrom algorithm that returns
all the nodes reachable from a partiuclar node.
static boolean pathBetween(Object A, Object B) {
// Base case
if (A.equals(B)) return true;
// Recursive case
for(Iterator Cs = nextNodes(A); Cs.hasMoreElements(); ) {
C = Cs.nextElement();
if pathBetween(C,B) return true;
}
return false;
} // reachable
+----+ | | v | A -> C -> D -> B
Is there a path from A to B?
Is B equal to A? No.
Pick some neighbor of A. C is the only one.
Is there a path from C to B?
Is B equal to C? No.
Pick some neighbor of C. Let's pick A.
Is there a path from A to B?
Is B equal to A? No.
Pick some neighbor of A. C is the only one.
Is there a path form C to B?
...
static boolean pathBetween(Object A, Object B) {
// Note that we've seen the current node.
mark(A);
// Base case
if (A.equals(B)) return true;
// Recursive case
for(Iterator Cs = nextNodes(A); Cs.hasMoreElements(); ) {
C = Cs.nextElement();
if (!marked(C) && pathBetween(C,B)) return true;
}
return false;
} // reachable
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
Source text last modified Tue Dec 2 10:50:23 1997.
This page generated on Tue Dec 2 10:52:06 1997 by SiteWeaver.
Contact our webmaster at rebelsky@math.grin.edu