Targeting (recursive algorithm) | (backtracking algorithm)

Source: Internet
Author: User

Interview example1:How many possibilities are there for a Shooting athlete to target a total of 10 rings and even a dozen or 90 rings? Use Recursive Algorithms for programming. [Interview questions for a famous communication enterprise in China]

Analysis: There are a total of 10 possibilities on the target: 1 to 10 rings, and may miss the target, that is, 0 rings. A total of 11 possibilities are added together. This is a loop and recursive interview question. In this program, we will use recursive methods to demonstrate all possible targets and calculate the results. Readers may ask, do we need to use recursion? Of course not. We can also use ten consecutive loop statements to represent the program. The Code is as follows:

For (I1 = 0; I1 <= 10; I1 ++)

{

For (I2 = 0; I2 <= 10; I2 ++)

{

For (I3 = 0; I3 <= 10; I3 ++)

{

......

For (I10 = 0; I10 <= 10; I10 ++)

{

If (I1 + I2 + I3 +... + I10 = 90)

Print ();

}

......

}

}

}

However, although the above loop program solves the problem, the time complexity and space complexity are undoubtedly very high. A better method is of course recursive. In fact, the company is designed like this. Recursive conditions are completed in the following four steps:

(1) In this case, even if each gun is behind 10 rings, the total number of loops cannot be 90. In this case, you do not need to play any more. Then exit recursion. The Code is as follows:

If (score <0 | score> (Num + 1) * 10) // The number of times num is 0 ~ 9

{

Return;

}

(2) if the conditions are met and the last time (because 10 times are required), the Code is as follows:

If (num = 0)

{

Store2 [num] = score;

Output (store2 );

Return;

}

(3) If the above two situations do not occur, execute recursion. The Code is as follows:

For (INT I = 0; I <= 10; ++ I)

{

// In fact, the order is reversed for convenience. store2 [9] is 1st

// The value of store2 [8] is 2nd ...... Store2 [0] Is 10th

Store2 [num] = I;

Cumput (score-I, num-1, store2 );

}

(4) print the function. if it meets the requirements, print it out. The Code is as follows:

Public static void output (INT [] store2)

{

For (INT I = 9; I> = 0; -- I)

{

Console. Write ("{0}", store2 [I]);

}

Console. writeline ();

Sum ++;

}

Answer:

The complete code written in C # is as follows:

Using system;

 

Public class M

{

 

// Public static int [] store;

// Equivalent to setting global variables

// The global variable sum is included in the M class.

Public static int sum;

Public M ()

{

Int sum = 0;

// Int [] store = {1, 2, 4, 5, 6, 7, 8, 9, 0 };

}

// Print the Function

// Print it out if it meets the requirements

Public static void output (INT [] store2)

{

For (INT I = 9; I> = 0; -- I)

{

Console. Write ("{0}", store2 [I]);

}

Console. writeline ();

Sum ++;

}

// Calculates the total number and returns the sum value.

Public static int sum2 ()

{

Return sum;

}

 

Public static void cumput (INT score, int num, int [] store2)

{

// If the total score exceeds 90 loops (that is, score <0), or if the remaining score is to be targeted

// The score is greater than 10 rings multiplied by the remaining number of hits, that is, even if the next round is played 10 rings

// If the number of times cannot be reached, exit recursion.

If (score <0 | score> (Num + 1) * 10) // The number of times num is 0 ~ 9

{

Return;

}

// If conditions are met and the last layer is reached

If (num = 0)

{

Store2 [num] = score;

Output (store2 );

Return;

}

For (INT I = 0; I <= 10; ++ I)

{

Store2 [num] = I;

Cumput (score-I, num-1, store2 );

}

// Console. Write ("{0}", store2 [5]);

}

}

 

Public class MyApp

{

Public static void Main ()

{

Int [] store;

Store = new int [10];

Int sum = 0;

// Int A = 90;

// Int B = 9;

// Output ();

M. cumput (90,9, store );

Sum = M. sum2 ();

// M. cumput2 (a, B, store );

// Console. Write ("{0}", store [3]);

// Cout <"Total:" <sum <Endl;

Console. Write ("Total: {0}", sum );

}

}

There are a total of 378 possible program results.

You can also write the code in C ++ as follows:

# Include <iostream>

Using namespace STD;

Int sum;

Int store [10];

Void output ()

{

For (INT I = 9; I> = 0; -- I)

{

Cout <store [I] <"";

}

Cout <Endl;

++ Sum;

}

 

Void cumput (INT score, int num)

{

If (score <0 | score> (Num + 1) * 10) // The number of times num is 0 ~ 9

Return;

If (num = 0)

{

Store [num] = score;

Output ();

Return;

}

For (INT I = 0; I <= 10; ++ I)

{

Store [num] = I;

Cumput (score-I, num-1 );

}

}

 

Int main (INT argc, char * argv [])

{

Cumput (90, 9 );

Cout <"Total:" <sum <Endl;

Return 0;

}

Interview Example 2:The eight queens issue is an ancient and famous issue and is a typical example of backtracking algorithms. This problem was proposed by the famous mathematician Gauss in the 19th century in 1850: Eight queens were placed on the 8x8 lattice International elephant board, so that they could not attack each other, that is to say, neither of the two queens can be in the same row, column, or diagonal line. [Interview questions for a famous British computer graphics and image Company]

Analysis: Recursive ImplementationNQueen's question.

Algorithm analysis:

Arrays A, B, and C are used to mark conflicts. array a indicates column conflicts, from a [0] to A [7] represents columns 0th to 7th. If a column already has a queen, it is 1; otherwise, it is 0.

Array B indicates the primary diagonal conflict, which is B [I-j + 7], that is, from B [0] ~ B [14]. If a principal has a queen on the diagonal line, the value is 1; otherwise, the value is 0.

Array C indicates the diagonal line conflict, which is C [I + J], that is, from C [0] ~ C [14]. If there is a queen on the diagonal line, the value is 1; otherwise, the value is 0.

The Code is as follows:

# Include <stdio. h>

 

Static char Queen [8] [8];

Static int A [8];

Static int B [15];

Static int C [15];

Static int iqueennum = 0; // record the total number of Board states

 

Void Qu (int I); // parameter I indicates the row

 

Int main ()

{

Int iline, icolumn;

 

// Initialize the board. The space is * and the place where the queen is placed is @

For (iline = 0; iline <8; iline ++)

{

A [iline] = 0; // column mark initialization, indicating no column conflict

For (icolumn = 0; icolumn <8; icolumn ++)

Queen [iline] [icolumn] = '*';

}

 

// Initialization of the master and slave diagonal marks, indicating no conflict

For (iline = 0; iline <15; iline ++)

B [iline] = C [iline] = 0;

 

Qu (0 );

Return 0;

}

 

Void Qu (int I)

{

Int icolumn;

 

For (icolumn = 0; icolumn <8; icolumn ++)

{

If (A [icolumn] = 0 & B [I-icolumn + 7] = 0 & C [I + icolumn] = 0)

// If no conflict exists

{

Queen [I] [icolumn] = '@'; // Add queen

A [icolumn] = 1; // mark, the next time this column cannot be placed as queen

B [I-icolumn + 7] = 1; // flag. The queen cannot be placed on the main diagonal line next time.

C [I + icolumn] = 1; // mark that the queen cannot be placed on the diagonal line next time

If (I <7) Qu (I + 1); // If the row is not completely traversed, enter the next row

Else // otherwise output

{

// Output the checkerboard status

Int iline, icolumn;

Printf ("status % d: \ n", ++ iqueennum );

For (iline = 0; iline <8; iline ++)

{

For (icolumn = 0; icolumn <8; icolumn ++)

Printf ("% C", Queen [iline] [icolumn]);

Printf ("\ n ");

}

Printf ("\ n ");

}

 

// If the placement of the Queen fails to meet the requirements in any case after the previous placement, the system will trace back and reset

Queen [I] [icolumn] = '*';

A [icolumn] = 0;

B [I-icolumn + 7] = 0;

C [I + icolumn] = 0;

}

}

}

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.