Java Reference
In-Depth Information
SR 12.7
Avoid recursion when the iterative solution is simpler and more easily
understood and programmed. Recursion has the overhead of multiple
method calls and is not always intuitive.
SR 12.8
If n < 0 a −1 is returned; otherwise the number of digits in the integer
n is returned.
SR 12.9
The recursive solution below is more complicated than the iterative
version, so it normally would not be done in this way.
// Returns 5 * num, assumes num > 0
private static int multByFive ( int num)
{
int result = 5; // when num == 1
if (num > 1)
result = 5 + multByFive(num - 1);
return result;
}
SR 12.10
Indirect recursion occurs when a method calls another method, which
calls another method, and so on until one of the called methods
invokes the original. Indirect recursion is usually more difficult to
trace than direct recursion, in which a method calls itself.
12.3 Using Recursion
SR 12.11
The MazeSearch program recursively processes each of the four posi-
tions adjacent to the “current” one unless either (1) the current posi-
tion is outside of the playing grid or (2) the final destination position
is reached.
SR 12.12
a. The original maze is defined when the grid array is declared and
initialized.
b. A test to see if we have arrived at the goal occurs at the second
if statement in the traverse method.
c. A location is marked as having been tried in the first statement
in the first if block of the traverse method.
d. A test to see if we already tried a location occurs in the second
if statement of the valid method.
SR 12.13
a. valid 0,0 valid 1,0 valid 2,0 valid 1,1
b. v alid 0,0
c. valid 0,0 valid 1,0 valid 2,0 valid 1,1 valid 0,0 va lid 1,-1
valid 0,1 valid 1,1 valid 0,2 valid -1,1 valid 0,0
valid -1,0 valid 0,-1
SR 12.14
The Towers of Hanoi puzzle of N disks is solved by moving N −1
disks out of the way onto an extra peg, moving the largest disk to
Search WWH ::




Custom Search