EightQueens
unknown
javascript
10 months ago
1.2 kB
4
Indexable
function EightQueens(){
const sol = new Array(8).fill(-1);
const solutions = [];
function IsSafe(row,col){
for (let i = 0; i < row; i++) {
//col
if(sol[i] === col){
return false;
}
//斜線
if(Math.abs(sol[i] - col) === Math.abs(i - row)){
return false;
}
}
return true;
}
function Solve(startRow){
if(startRow===8){
solutions.push([...sol]);
return;
}
for(let col = 0;col<8;col++){
if(IsSafe(startRow,col)){
sol[startRow]=col;
Solve(startRow+1);
}
}
}
function PrintSolutions(){
for(let i = 0;i<solutions.length;i++){
const header = 'Solution:'+(i+1).toString();
console.log(header);
const s=solutions[i];
for(let row = 0;row<8;row++){
let rowString = "";
for(let col=0;col<8;col++){
if(col===s[row]){
rowString += 'Q';
}else{
rowString += '.';
}
}
console.log(rowString);
}
}
}
Solve(0);
PrintSolutions();
}
EightQueens();Editor is loading...
Leave a Comment