Leetcode #52 N-queens II

Source: Internet
Author: User

Title Link: https://leetcode.com/problems/n-queens-ii/

The bitwise operation of the N queen problem is realized.

1 classSolution2 {3  Public:4     intTotalnqueens (intN)5     {6Upperlimit = (1<< N)-1;//if n is 8, then Upperlimit is "11111111". 7Placequeen (0,0,0);8 9         returncount;Ten     } One  A     voidPlacequeen (intDownintLeftintRight//Down : Just below/left: bottom Right  -     { -         intAvailablebits =0;//A bit of "1" in availablebits, indicating that the position can be placed in the Queen.  the  -         if(down = = Upperlimit)//a "1" is placed underneath all locations, where all positions are placed.  -         { -++count; +         } -         Else +         { A             //The "1" in the Left | Right is the position occupied by the other queens, and the "1" indicates the position of the Queen.  atAvailablebits = upperlimit & (~ | left |Right )); -              while(availablebits) -             { -                 //Remove the rightmost "1" in the availablebits, such as Availablebits = "11110000", and the result is "00010000" -                 //Place the next queen in the "1" position and remove the "1" from the availablebits.  -                 intNextqueen = availablebits & (-availablebits); inAvailablebits-=Nextqueen; -  to                 //recursively call, place the next queen, and consider the effect on the next line: +                 //The status changes to (Down | nextqueen, (left | nextqueen) << 1, (right | nextqueen) >> 1).  -                 //The effect on the left diagonal, corresponding to the lower-left position, and the effect on the right diagonal, corresponds to the lower-right position.  thePlacequeen (Down | nextqueen, (left | nextqueen) <<1, (right | nextqueen) >>1); *             } $         }Panax Notoginseng     } -  the     intUpperlimit =0; +     intCount =0; A};

Leetcode #52 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.