Recursive Algorithms for data structures and algorithms C ++ and PHP, and data structures and algorithms Recursion

Source: Internet
Author: User

Recursive Algorithms for data structures and algorithms C ++ and PHP, and data structures and algorithms Recursion
Recursive Algorithm: it is an algorithm that calls itself directly or indirectly. Implementation process: You can use a function or sub-process to complete recursive operations by directly or indirectly calling the code in a function or sub-process. (For a problem of the same category, the problem is converted into a subproblem of scale-down to a minimum problem with known conditions. Then, the problem is solved and the result is returned step by step. It is actually a loop .) Major manifestation: a small amount of code solves very complicated problems. 1. recursion is to call itself in a method. 2. A clear recursion termination condition must exist, which is called a recursion exit. 3. It is concise but inefficient. Generally, it is not recommended to use 4. The return points and local variables of each layer open up stacks for storage. Excessive recursion times may cause stack overflow.
Example 1: Calculate the factorial C ++ code:

# Include <iostream> int factorial (int n); int main () {using namespace std; int n; cout <"enter a number:"; cin> n; cout <n <"factorial:" <factorial (n) <endl; return 0;} int factorial (int n) {if (n = 1) return 1; return n * factorial (n-1 );}
Running result:
Instance 2: Numeric Conversion
Code:
# Include <iostream> # include <cstring> void feelTheBase (char * s, int n, int sys); int main () {using namespace std; char s [60]; int n, sys; cout <"enter an integer:"; cin> n; cout <"Enter the hexadecimal type (, 16) to be converted ): "; cin> sys; feelTheBase (s, n, sys); cout <n <" converted to "<sys <" hexadecimal result: "<s <endl; return 0;} void feelTheBase (char * s, int n, int sys) {char bit [] = {" 0123456789 ABCDEF "}; int len; if (n = 0) {strcpy (s, ""); return;} feelTheBase (s, n/sys, sys); len = strlen (s ); s [len] = bit [n % sys]; s [len + 1] = '\ 0 ';}
Running result:

Example 3: List all subdirectories and files in a directory (you can also use the scandir function for more convenience) PHP implementation code:
<? Phpfunction rec ($ dir, $ lev= 0) {$ dh = opendir ($ dir); while ($ file = readdir ($ dh ))! = False) {if ($ file = '. '| $ file = '.. ') {continue;} if (is_dir ($ dir. '/'. $ file) {$ arr = explode ("/", $ dir. '/'. $ file); $ lev= count ($ arr)-3; echo str_pad ('', $ lev ,"--"). "directory ". $ file. "<br/>"; rec ($ dir. '/'. $ file, $ lev+ 1);} else {echo str_pad ('', $ lev ,"--"). $ file. "<br/>" ;}} closedir ($ dh);} $ dir = ". /"; rec ($ dir);?>
Running result:


Data Structure algorithm (c) maze Solution

The annotations are very detailed and I hope they will help you.
# Include <stdio. h>
# Include <stdlib. h>
# Define M 15
# Define N 15
Struct mark // defines the coordinate type of the Interior Point of the maze
{
Int x;
Int y;
};

Struct Element // "Lian" Stack Element, hey ..
{
Int x, y; // x rows, column y
Int d; // the next step of d.
};

Typedef struct LStack // chain Stack
{
Element elem;
Struct LStack * next;
} * PLStack;

/************* Stack function ****************/

Int InitStack (PLStack & S) // construct an empty Stack
{
S = NULL;
Return 1;
}

Int StackEmpty (PLStack S) // determines whether the stack is empty.
{
If (S = NULL)
Return 1;
Else
Return 0;
}

Int Push (PLStack & S, Element e) // press the New Data Element
{
PLStack p;
P = (PLStack) malloc (sizeof (LStack ));
P-> elem = e;
P-> next = S;
S = p;
Return 1;
}

Int Pop (PLStack & S, Element & e) // stack top Element output Stack
{
PLStack p;
If (! StackEmpty (S ))
{
E = S-> elem;
P = S;
S = S-> next;
Free (p );
Return 1;
}
Else
Return 0;
}

******************** ***/
Void MazePath (struct mark start, struct mark end, int maze [M] [N], int diradd [4] [2])
{
Int I, j, d; int a, B;
Element elem, e;
PLStack S1, S2;
InitStack (S1 );
InitStack (S2 );
Maze [start. x] [start. y] = 2; // mark the entry point
Elem. x = start. x;
Elem. y = start. y;
Elem. d =-1; // start with-1
Push (S1, elem );
While (! StackEmpty (S1) // the stack is not empty. A path is available.
{
Pop (S1, elem );
I = elem. x;
J = elem. y;
D = elem. d + 1; // The next direction
While (d <4) // test all directions in the Southeast and Northwest China
{
A = I + diradd [d] [0];
B = j + diradd [d] [1];
If (a = end. x & B = end. y & maze [a] [B] = 0) // if the exit is reached
{
Elem. x = I;
Elem. y =... the remaining full text>

Teaches the correspondence between data structures and algorithms, for example, recursive algorithms correspond to stacks, and extended search maps to queues.

I personally think that after learning about the data structure, I can look at the implementation of the algorithm. Sometimes I may feel like I have known each other before. I just want to say that the search, depth, and breadth are good, anyway, you need to abstract a node, which is a bit similar to the node of the linked list. The deep search and wide search are also related to the tree. One is to search for each branch, one is to search for each layer, and the Backtracking process of deep search also uses recursion, which also corresponds to the stack. Therefore, I think it doesn't matter who corresponds to this kind of thing, he is familiar with the characteristics of each data structure and flexible application.
The above is a bit of understanding when I am studying. I hope it will be helpful to you.
Again, it seems that the queue features, that is, first-in-first-out, and linked lists can also be used for implementation.

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.