[Leetcode] N-queens II

Source: Internet
Author: User

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

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.