Java Reference
In-Depth Information
Fig. 18.19 | Drawing the “Lo feather fractal” using recursion. (Part 4 of 4.)
Lines 27-50 define the recursive method that creates the fractal. This method takes
six parameters: the level, four integers that specify the x- and y -coordinates of two points,
and the Graphics object g . The base case for this method (line 31) occurs when level
equals 0, at which time a line will be drawn between the two points given as parameters.
Lines 36-43 calculate ( xC , yC ), the midpoint between ( xA , yA ) and ( xB , yB ), and ( xD , yD ),
the point that creates a right isosceles triangle with ( xA , yA ) and ( xC , yC ). Lines 46-48 make
three recursive calls on three different sets of points.
In method paintComponent , line 60 makes the first call to method drawFractal to
start the drawing. This method call is not recursive, but all subsequent calls to draw-
Fractal performed from the body of drawFractal are. Since the lines will not be drawn
until the base case is reached, the distance between two points decreases on each recursive
call. As the level of recursion increases, the fractal becomes smoother and more detailed.
The shape of this fractal stabilizes as the level approaches 11. Fractals will stabilize at dif-
ferent levels based on their shape and size.
The output of Fig. 18.19 shows the development of the fractal from levels 0 to 6. The
last image shows the defining shape of the fractal at level 11. If we focus on one of the arms
of this fractal, it will be identical to the whole image. This property defines the fractal to
be strictly self-similar.
18.10 Recursive Backtracking
Our recursive methods all have a similar architecture—if the base case is reached, return a
result; if not, make one or more recursive calls. This section explores a more complex re-
cursive technique that finds a path through a maze, returning true if there's a possible so-
lution. The solution involves moving through the maze one step at a time, where moves
can be made by going down, right, up or left (diagonal moves are not permitted). From
the current location in the maze (starting with the entry point), the following steps are tak-
en: For each possible direction, the move is made in that direction and a recursive call is
made to solve the remainder of the maze from the new location. When a dead end is
 
Search WWH ::




Custom Search