[Programmer interview questions selected 100 questions] 58. Eight queens question, programmer 58
Question
Eight queens are placed on 8x8 chess sets so that they cannot attack each other. That is, two queens cannot be on the same row, column, or diagonal slashes. Each black lattice in represents a queen, which is a qualified placement method. The total number of requests.
Ideas
This is the famous Eight queens question. Recursion is usually required to solve this problem, while recursion requires a high programming capability. Therefore, many interviewers prefer this topic to examine the applicant's ability to analyze complex problems and programming skills.
Because any two of the eight queens cannot be in the same row, this must be because every queen occupies one row. Therefore, we can define an array of colIndex [8]. colIndex [I] indicates the Queen's column number in row I. First, initialize the eight numbers of colIndex with 0-7 respectively. Next, we need to arrange the array colIndex in full. Since we use different numbers to initialize numbers in the array, any two queens must have different columns. We only need to determine whether the eight queens corresponding to each arrangement are on the same diagonal slashes, that is, the two subscripts I and j of the array, is it I-j = colIndex [I]-colIndex [j] Or j-I = colIndex [I]-colIndex [j]?
For details about full sorting, refer to [LeetCode] 46. Permutations
Code
/* ---------------------------------- * Date: 2015-04-04 * Author: SJF0115 * Title: 58. eight Queen's questions * Source: programmer interview questions featured 100 questions --------------------------------------- */# include <iostream >#include <vector> using namespace std; // determine whether the Queen is on the same diagonal bool Check (vector <int> colIndex, int n) {bool a, B; for (int I = 0; I <n; ++ I) {for (int j = I + 1; j <n; ++ j) {a = (I-j = colIndex [I]-colIndex [j]); B = (j-I = colIndex [I]-colIndex [J]); if (a | B) {return false;} // if} // for return true ;} // void Permutation (vector <int> & colIndex, int n, int index, int & count, vector <bool> & visited) {if (index = n) {// determine whether the Queen is on the same diagonal line if (Check (colIndex, n) {++ count; for (int I = 0; I <n; ++ I) {cout <colIndex [I] <"" ;}// for cout <endl ;}// if return ;}// if for (int I = 0; I <n; ++ I) {// determine whether the if (! Visited [I]) {colIndex [index] = I; visited [I] = true; Permutation (colIndex, n, index + 1, count, visited ); visited [I] = false;} // if} // for} int EightQueen () {int count = 0; int n = 8; // colIndex [I] indicates the Queen's column number vector <int> colIndex (n, 0) in row I; vector <bool> visited (n, false ); permutation (colIndex, n, 0, count, visited); return count;} int main () {// freopen ("C: \ Users \ Administrator \ Desktop \ c00000000.txt "," r ", stdin); cout <EightQueen () <endl; return 0 ;}