[Original] backtracking (combination problem, eight queens Problem)

Source: Internet
Author: User
Document directory
  • 1.1. Combination Problems
  • 1.2. Eight queens
[Title] [original] Backtracking Method (combination problem, eight queens Problem)
[Date] 2013-03-29
【Abstract】 examples of the Backtracking Method include the combination problem and the eight queens problem. I copied it in a book a long time ago. I will review it and share it with you. You can use a single word (partially simplified) to mark the original, and the copyright belongs to the original author.
[Keywords] algorithm, algorithm, and backtracking method
[Environment] Windows 7
Author wintys (wintys@gmail.com) http://wintys.cnblogs.com
URL http://www.cnblogs.com/wintys/archive/2013/03/29/algorithm_backtracking.html

[Content ]:
1. Key Points of backtracking

Backtracking: first, discard the size restriction.
A. Test (scale up): Scale up if all conditions except scale are met.
B. backtracing (scale down): backtracing is performed when the current scale solution is not a legal solution (constraints are not met). backtracing is required when a solution is obtained and the next solution is obtained.
 
1.1. Combination Problems

Problem description: Find all the combinations of the number of r from the natural number 1, 2,..., n.
[Analysis ]:
Use the backtracking method to find the solution to the problem and save the found combination in the ascending order of a [0], a [1],..., in a [r-1], the elements of the combination meet the following properties:
(1) a [I + 1]> a [I], the last data word is larger than the previous number.
(2) a [I]-I <= n-r + 1.
 
[Pseudocode] void combination (int n, int r)
{
Int I, j;
// Search depth and breadth Initialization
I = 0;
A [I] = 1;
 
Do {
If (a [I]-I <= n-r + 1) // constraints on depth and breadth, nature (2)
{
If (I = r-1) // scale meets requirements
{
Print a [0 .. r-1]; // output a group of qualified Solutions
A [I] ++; // The next solution of the current scale, that is, increasing the breadth
Continue;
}
I ++; // expand the problem scale, that is, increase the depth
A [I] = a [I-1] + 1; // satisfies the nature (1)
}
Else // check the current scale and trace back.
{
If (I = 0) // go back to the beginning. You have found all solutions to the problem and the search is complete.
Return;
A [-- I] ++; // scale down and examine the next solution to reduce the depth and increase the breadth.
}
} While (1 );
}

1.2. Eight queens

Problem description: Find all the la s of n Chinese chess "Queens" on an nxn chessboard.
[Analysis]
A. the intuitive method is to use a two-dimensional array, but after careful observation, we will find that this representation method makes it difficult to adjust the solution and check its rationality. A better way is to express frequently-used information as directly as possible. For this question, common information is not the specific location of the Queen, but whether "A queen" has been properly placed in a certain diagonal line. Only one queen can be placed in a column, so the col [] array is introduced.
B. in order for the program to trace back to the original position after finding the complete partial solution, the initial value of col [0] is set to 0. When it goes back to column 0th, it indicates that all solutions have been obtained and the program ends.
C. Each row, column, and slash can have only one queen. The array is introduced to check whether the Queen is placed properly. If the value is 1, there is no queen. If the value is 0, there is a queen.
Array a [k] indicates that there is no queen on row k.
Array B [k] indicates no queen on the Right high left low diagonal line (/) of column k.
Array c [k] indicates no queen on the Left high right low slash (\) of column k.
D. the square on the same right-high left-low diagonal line (/) in the checker. The sum of their row numbers and column numbers is the same; the square on the same left-high right-low diagonal line, their row numbers are the same as the column numbers.
E. initially, there was no queen on all rows and diagonal lines, starting with configuring the first queen in the first row of column 1st, when a reasonable queen is placed in column m col [m, in arrays a [], B [], and c [] are column m, and the position of row col [m] is set with the Queen mark; when you go back from column m to M-1 are ready to adjust the Queen configuration of column m, clear the Queen's flag for M-1 in arrays a [], B [], and c. The configuration of a queen in the column m is reasonable in the cell of col [m]. The values of the positions of arrays a [], B [], and c [] are both 1. Because only one queen is configured in a column at a time, it is impossible to have two queens in the same column.
F. The number of columns in the board m is called the scale of the problem.
G. the key to this program is the test condition: a [col [m] & B [m + col [m] & c [n + m-col [m];
 
 
[Code] # include <stdio. h>
# Include <stdlib. h>
# Define MAX_N 20
 
Int n, m, good;
Int col [MAX_N + 1], a [MAX_N + 1], B [2 * MAX_N + 1], c [2 * MAX_N + 1];
 
Void main ()
{
Int j;
Char awn;
Printf ("Enter n :");
Scanf ("% d", & n );
 
For (j = 0; j <= n; j ++) a [j] = 1; // At the beginning, each column can be placed as a queen.
For (j = 0; j <= 2 * n; j ++) B [j] = c [j] = 1; // At the beginning, each diagonal line can be placed as a queen.
M = 1; col [1] = 1; good = 1; col [0] = 0;
 
Do {
If (good)
{
If (m = n) // locate a solution
{
Printf ("column \ t row ");
For (j = 1; j <= n; j ++)
Printf ("% 3d \ t % 3d \ n", j, col [j]); // output the Queen's location
Scanf ("% c", & awn );
If (awn = 'q' | awn = 'q') exit (0 );
While (col [m] = n) // check whether there are other solutions to the current size of m.
{
M --; // the current scale m. If there is no other solution, it will be traced back.
A [col [m] = B [m + col [m] = c [n + m-col [m] = 1; // clear the Queen's logo after backtracking
}
Col [m] ++; // test the next solution of the current scale
}
Else // In the m column and col [m], set the Queen flag
{
A [col [m] = B [m + col [m] = c [n + m-col [m] = 0;
Col [++ m] = 1; // expand the scale and test the first possible solution under the scale, that is, the Queen's configuration starts from the first line.
}
}
Else // when good is 0, that is, the trial solution fails at the current scale. You need to trace back or adjust the location of the Queen.
{
While (col [m] = n) // determines whether all possible test attempts at the current scale fail.
{
M --; // all possible test attempts at the current scale fail and need to be traced back
A [col [m] = B [m + col [m] = c [n + m-col [m] = 1; // After backtracking, clear the Queen's logo.
}
Col [m] ++; // there may be other solutions under the current scale to adjust the Queen's position under the current scale.
}
// Is the current Queen placed under m valid?
Good = a [col [m] & B [m + col [m] & c [n + m-col [m];
} While (m! = 0 );
}

[Reference]

[1] Software Designer exam site analysis and question details (Latest Version)

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.