Test instructions
Follow up for n-queens problem.
Now, instead outputting board configurations and return the total number of distinct solutions.
Ideas:
N Queen question, count the number of possible scenarios. The basic simple idea is to deal with each line, try to put a queen in each column, as long as there is no conflict, recursive downward, constantly calculate the number of legitimate programs.
Code:
C++
Class Solution {Public:int totalnqueens (int n) {/* Initialize vector variable, number I represents the queen of line I is in which column */Vector<int> ; Chess (n,-1); int ans = 0; /* Solve the problem */Solvequeen (0,n,chess.begin (), ans); return ans; } void Solvequeen (int r,int n,vector<int>::iterator chess,int &ans) {/*r equals n when each row has Queen */I F (r = = N) {ans++; Return }/* To see which column of the current row can be put Queen */for (int i = 0;i < N;++i) {* (chess+r) = i; /* Check legality */if (check (chess,r,n)) {/* down recursion */Solvequeen (R+1,n,chess,ans); }}}/* Check for conflicts */bool Check (Vector<int>::iterator chess,int r,int N) {/* For each previous row */for (int i = 0;i < R;++i) {/* calculates the distance between two columns */int dis = ABS (* (CHESS+R)-* (Chess+i)); /* dis = 0 in the same column, dis = r-1 constitutes isosceles triangle, i.e. diagonal */if (dis = = 0 | | dis = = r-i) return false; } return true; }};Python:
Class solution: # @return An integer def totalnqueens (self, N): Self.array = [0 for I in range (0,n)] self . Ans = 0 self.slovequeen (0,n) return Self.ans def slovequeen (self,r,n): if r = = N: Self.ans + = 1 return for I in range (0,n): self.array[r] = i if Self.check (r,n): self.slovequeen (R+1,n) def check (self,r,n): For I in range (0,r): dis = ABS (Self.array[r]-self.array[i]) if dis = = 0 or dis = = R-i: return False return True
"Leetcode" N-queens II