If you had solved the n-queens problem, this one can be solved in a similar manner. Starting from the first row, we try each of its columns. If There is no attack, we move on to the next row based previous rows. Otherwise, we backtrack to the current row and try another selection of column position. Once We meet the last row, increase the counts by 1.
The code is as follows.
1 classSolution {2 Public:3 intTotalnqueens (intN) {4 int* Colpos =New int[n];5 intCounts =0;6Solve (Colpos, N,0, counts);7 DeleteColpos;8 returncounts;9 }Ten Private: One BOOLNoattack (int*& Colpos,intRowintCol) { A for(intR = Row-1, ld = col-1, rd = col +1; R >=0; R--, LD--, rd++) - if(Colpos[r] = = Col | | colpos[r] = = LD | | colpos[r] = =Rd) - return false; the return true; - } - voidSolveint*& Colpos,intNintRowint&counts) { - if(Row = =N) { +counts++; - return; + } A for(intCol =0; Col < n; col++) { atColpos[row] =Col; - if(Noattack (Colpos, Row, col)) -Solve (Colpos, n, Row +1, counts); - } - } -};
Someone have even suggested a damn clever solution to this problem using bit-manipulations on this link (refer to the first Answer).
I rewrite the code below for reference.
1 classSolution {2 Public:3 intTotalnqueens (intN) {4 intCounts =0;5 intLimit = (1<< N)-1;6Solve0,0,0, limit, counts);7 returncounts;8 }9 Private:Ten voidSolveintHProj,intLProj,intRProj,intLimitint&counts) { One if(HProj = =limit) { Acounts++; - return; - } the intpos = limit & (~ (hProj | lProj |rProj)); - while(POS) { - intp = pos & (-POS); -POS ^=p; +Solve (HProj | p, (lProj | p) >>1, (RProj | p) <<1, limit, counts); - } + } A};
[Leetcode] N-queens II