Java implements a simple recursive operation __java

Source: Internet
Author: User

In the data structure algorithm design, or a method of concrete implementation, there is a method called "recursion", this method is not particularly difficult in mind, but there are some need to pay attention to the implementation. Although for many recursive algorithms can be replaced by the corresponding cyclic iterations, but for some more abstract complex algorithm without recursion is difficult to understand and implement.
Recursive is divided into direct recursion and indirect recursion, simply share two small direct recursion.
For the concept of recursion, in fact, you can easily understand the definition of their own, remember a child saw a TV series "Wolf Poison Flower", the protagonist is called "often hair", but an illiterate, the teacher asked his name, he said "often hair." "which often. "Often hair often." "which hair." "" The hair of the regular hair ah. Results The second class teacher let a group of children together shouted "often hair, often hair, fool's silly, fool's melon". Again, it's clear that in most cases recursion is a reasonable way to interpret an idea or definition. Recursion in thought is analogous to the mathematical induction that has been learned in mathematics.
Implementation of recursion:
The implementation of recursion should note that there are two points: a recursive option and a non recursive option, which becomesBase Case(base case). The underlying situation is the recursive end case, where there is no underlying situation or bad handling that results in infinite recursion, which we do not want.The most important thing in recursion is to deal with the basic situation. In combination with specific cases, say recursion.BacktrackingThe process.
Below to write two small programs:
1, stair climbing algorithm: Known a staircase has n steps, each can choose to take a step or two steps, to go through a total number of different ways to go.
The method is as follows:

Recursive functions have a bit more trouble than return values, because a function has only one return value, but recursion requires the existence of a base case, so there must be an if judgment to terminate recursion. So there is a return behind every if or else, so that the function is in either case and has only one returned value.
Analyze This algorithm:
A: If there are 0 steps, then there are 0 ways to go, this needless to say;
B: If there are 1 steps, then there are 1 ways to go;
C: If there are 2 steps, then there are 2 ways to go (walk 1 at a time, walk two times; walk two at a time);
The above B and C are the basic situations.
D: The next is recursion, if the number of steps more than 2, then first step there are two options: the first walk 1, or the first time to walk two. In this way there are two situations except for the first walk: Climbstairs (n-1) and Climbstairs (n-2). This continues until it appears to the underlying situation (i.e. n==1 or n==2), recursively to this place (the underlying case), and then beginsBacktracking, which is called "backtracking", which is closely related to recursion. Backtracking, as its name implies, goes backwards from the result, finding the whole process, and then analyzing the path or the process of realization.

It should be noted that this algorithm to achieve a simple idea, but the complexity is not reduced, but also involves backtracking to save the stack problem, and in the number of steps to a certain number of times will be out of bounds (the number of trips will exceed the scope of the int), so the recursive program is largely the idea of the realization of the design of a simple understanding.
Below is the source code:

Package Leetcode;

public class Climbstairs {
//  **************************************************************
    Public int climbstairs (int n) {
        int i=1;
         if (n<=0) return
            0;
         if (n==1) {return
             i;
         }
         if (n==2) {
             i++;
             return i;
         }
         else return
             climbstairs (n-1) +climbstairs (n-2);
   }
Public
     static void main (String []args) {
         climbstairs cs=new climbstairs ();
         int a =cs.climbstairs (4);
         System.out.println (a);
     }

Then there are a few more typical recursion problem: for example, maze problem, or the most classic of the Nottingham tower problem, below are given the source code, we study together.

Hanoi Tower Problem: You can only move one plate at a time; you can't put a large plate on a small plate, except for the moment the plate moves between two columns, the plate must be on the post. (at these three points, move the plate from the start pillar A to the target pillar C)

The code is as follows:
Base case: N==1 to terminate recursion and backtrack.

public class Hannuotower {public
    void tower (int n,char S,char M,char e)//n Towers are moved from S through M eventually to e
    {
        if (n==1)
            Move (s,e);
        else
        {
            Tower (n-1,s,e,m);
            Move (s,e);
            Tower (n-1,m,s,e);
        }
    public void Move (char S,char e) {
        System.out.println (' Move ' +s+ ' to ' +e);
    }
    public static void Main (String []args) {
        hannuotower hnt =new hannuotower ();
        Hnt.tower (4, ' A ', ' B ', ' C ');
    }

Maze approach: two-dimensional arrays constitute a maze, 1 means the path, 0 is not, find a path from the starting point (Traverse function parameters) to the end point (lower right corner).

Basic situation: row==grid.length-1&&column==grid[0].length-1 when done=true;

public class Maze {private final int tried=3;

    private final int path=7;
                                        private int [] grid={{1,1,1,0,0,1,0,1,0,0}, {0,0,1,1,1,0,0,0,0,0},
                                        {1,0,1,0,0,0,1,1,1,1}, {1,1,1,1,1,0,0,0,1,1},
                                        {0,0,0,0,1,1,1,0,0,0}, {1,0,1,0,1,0,0,1,0,0},
    {1,0,0,1,1,1,1,1,1,1}};
        public boolean traverse (int row,int column) {Boolean done =false;
            if (valid (Row,column)) {grid[row][column]=tried;
            if (row==grid.length-1&&column==grid[0].length-1) done=true; else {done=traverse (row+1,column);//down if (!done) done=t Raverse (row,column+1);//right if (!done) Done=traverse (row-1, column);//up if (!done) done=traverse (row,column-1);//left} i
        F (done) Grid[row][column]=path;
    return done;
        Private Boolean valid (int row,int column) {Boolean result=false; if (row>=0&&row<grid.length&&column>=0&&column<grid[row].length) if (Grid[ro
        W][column]==1) Result=true;
    return result;
        public string toString () {string result= ' \ n ';
                for (int row=0;row<grid.length;row++) {for (int column=0;column<grid[row].length;column++) {
            Result +=grid[row][column]+ "";
        } result+= "\ n";
    return result;
        public static void Main (String []args) {Maze maze=new Maze ();
        System.out.println (Maze); if (maze.traverse (0, 0)) System.out.println ("The Maze was successfully travelled!");
        else System.out.println ("There is no possible path.");
    System.out.println (Maze);
 }

}

Run Result:

If there is no place to be, also hope that your great God advice.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.