Eight queens Problem: recursive and non-recursive Solutions

Source: Internet
Author: User
# Include <iostream> # include <vector> using namespace STD; # define maxnum 10int tot = 0, row, line [maxnum], n = 8; void search (INT row) // recursive search for feasible solutions {int I, j; If (ROW = N) tot ++; // when ROW = N, the queen of each row does not conflict, that is, the feasible solution else for (I = 0; I <n; I ++) {int OK = 1; line [row] = I; // try to put the queen of row in column I for (j = 0; j <row; j ++) // check whether it is in conflict with the Queen. {If (line [row] = line [J] | line [row]-line [J] = row-j | | line [J]-line [row] = row-j) {OK = 0; break; // if a conflict exists, stop Search: returns the first-level Recursive Backtracking. The key to efficient backtracking.} If (OK) Search (row + 1) ;}} const int n = 8; // recursive int CNT = 0; void DFS (INT layer, int Col, int left, int right) {If (n = Layer) {CNT ++; return;} int TMP = ~ (COL | left | right); // bitwise result! For (INT I = 0; I <n; I ++) {If (TMP & (1 <I )) // Yes & No & {int T1 = Col | (1 <I), T2 = (left | (1 <I)> 1, t3 = (right | (1 <I) <1; // DFS (layer + 1, Col & (1 <I ), (left & (1 <I) <1, (Right & (1 <I)> 1); DFS (layer + 1, T1, T2, t3) ;}}int main () {tot = 0; n = 8; search (0); cout <tot <Endl; DFS (0, 0, 0 ); cout <CNT <Endl; System ("pause"); Return 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.