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