Skip to content

Commit 24e70f2

Browse files
committed
Add N queens problem bitwise solution
1 parent 99bef39 commit 24e70f2

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# N-Queens Problem with Bitwise Solution
2+
3+
Write a function that will find all possible solutions to the N queens problem for a given N.
4+
5+
## References
6+
7+
- [Wikipedia](https://en.wikipedia.org/wiki/Eight_queens_puzzle)
8+
- [GREG TROWBRIDGE](http://gregtrowbridge.com/a-bitwise-solution-to-the-n-queens-problem-in-javascript/)
9+
- [Backtracking Algorithms in MCPL using Bit Patterns and Recursion](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.51.7113&rep=rep1&type=pdf)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import nQueensBitwise from '../nQueensBitwise';
2+
3+
describe('nQueensBitwise', () => {
4+
it('should have solutions for 4 to N queens', () => {
5+
const solutionFor4 = nQueensBitwise(4);
6+
expect(solutionFor4).toBe(2);
7+
8+
const solutionFor5 = nQueensBitwise(5);
9+
expect(solutionFor5).toBe(10);
10+
11+
const solutionFor6 = nQueensBitwise(6);
12+
expect(solutionFor6).toBe(4);
13+
14+
const solutionFor7 = nQueensBitwise(7);
15+
expect(solutionFor7).toBe(40);
16+
17+
const solutionFor8 = nQueensBitwise(8);
18+
expect(solutionFor8).toBe(92);
19+
20+
const solutionFor9 = nQueensBitwise(9);
21+
expect(solutionFor9).toBe(352);
22+
23+
const solutionFor10 = nQueensBitwise(10);
24+
expect(solutionFor10).toBe(724);
25+
});
26+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
export default function(n) {
2+
//Keeps track of the # of valid solutions
3+
var count = 0;
4+
5+
//Helps identify valid solutions
6+
var done = Math.pow(2,n) - 1;
7+
8+
//Checks all possible board configurations
9+
var innerRecurse = function(ld, col, rd) {
10+
11+
//All columns are occupied,
12+
//so the solution must be complete
13+
if (col === done) {
14+
count++;
15+
return;
16+
}
17+
18+
//Gets a bit sequence with "1"s
19+
//whereever there is an open "slot"
20+
var poss = ~(ld | rd | col);
21+
22+
//Loops as long as there is a valid
23+
//place to put another queen.
24+
while ( poss & done ) {
25+
var bit = poss & -poss;
26+
poss -= bit;
27+
innerRecurse((ld|bit)>>1, col|bit, (rd|bit)<<1);
28+
}
29+
};
30+
31+
innerRecurse(0,0,0);
32+
33+
return count;
34+
};

0 commit comments

Comments
 (0)