Last active
August 29, 2015 13:56
-
-
Save GZShi/9132895 to your computer and use it in GitHub Desktop.
One solution to the eight queens puzzle in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var solves = []; | |
var ans = []; | |
function solve_eight_queens (ans, line) { | |
if(line >== 8) { | |
solves.push(ans); | |
return true; | |
} else { | |
for (var row = 0; row < 8; ++row) { | |
var fine = true; | |
for (var i = 0; i < ans.length; ++i) { | |
if(ans[i] === row | |
|| line - i === row - ans[i] | |
|| line - i === ans[i] - row) { | |
fine = false; | |
break; | |
} | |
} | |
if(fine) { | |
ans.push(row); | |
solve_eight_queens(ans, line + 1); | |
ans.pop(); | |
} | |
} | |
} | |
} | |
console.time('solve'); | |
solve_eight_queens(ans, 0); | |
console.timeEnd('solve'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment