//8 queens (backtracking) #include <iostream> using namespace std; void queen_all(int k);//The algorithm function of backtracking int col[9]; bool row[9], digLeft[17], digRight[17]; intmain() { int j; for (j = 0; j <= 8; j++) row[j] = true; for (j = 0; j <= 16; j++) digLeft[j] = digRight[j] = true; queen_all(1); return 0; } //Find a reasonable configuration on the Kth column of the 8*8 chessboard void queen_all(int k) { int i, j; char awn; //Store the flag of whether to continue searching for (i = 1; i <= 8;i++) //Configure the queens of K columns on rows 1 to 8 in turn if (row[i] && digLeft[k+i-1] && digRight[8+k-i]){ //可行位置 col[k] = i; //indicates row i at column K row[i] = digLeft[k+i-1] = digRight[8+ki] = false; // means there is a queen if (k == 8){ //find a feasible solution for (j = 1; j <= 8; j++) cout << j << " " << col[j] << '\t'; //列和行 cout << endl << "Do you need to continue searching (Q-- means exit, others continue:)"; cin >> awn; if (awn == 'Q'|| awn == 'q') exit(0); } else queen_all(k + 1); // recurse to column k+1 row[i] = digLeft[k+i-1] = digRight[8+ki] = true; // prepare for the next feasible solution } }
8 Queens Problem (Backtracking)
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326502061&siteId=291194637
Recommended
Ranking