Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Created September 3, 2016 06:16
Show Gist options
  • Save alphaKAI/6535f3ee4285f44824b39e8dab863657 to your computer and use it in GitHub Desktop.
Save alphaKAI/6535f3ee4285f44824b39e8dab863657 to your computer and use it in GitHub Desktop.
N-Queen Solver with backtracking in D
//N-Queen Solver with backtracking in D
import std.algorithm,
std.range,
std.stdio,
std.conv;
enum N = 8;
string rep(string ptn, size_t n) {
string ret;
foreach (_; n.iota) {
ret ~= ptn;
}
return ret;
}
enum llen = N.to!string.length;
enum padq = " ".rep(llen - 1);
enum pads = "-".rep(llen - 1);
size_t[N][N] board;
size_t[2][N] queens;
N abs(N, M)(N n, M m) if (is(N == M)) {
return (n - m) * ((n - m) < 0 ? -1 : 1);
}
void changeBoard(size_t x, size_t y, int val) {
foreach (k; N.iota) {
board[k][x] += val;
board[y][k] += val;
}
if (y > x) {
foreach (k; (N - (y - x)).iota) {
board[k + (y - x)][k] += val;
}
} else {
foreach (k; (N - (x - y)).iota) {
board[k][k + (x - y)] += val;
}
}
if (x + y < N) {
foreach (k; (x + y + 1).iota) {
board[k][x + y - k] += val;
}
} else {
foreach (k; (x + y + 1 - N).iota(N)) {
board[k][x + y - k] += val;
}
}
}
int total;
void seqQueen(size_t founds = 0) {
if (founds == N) {
total++;
bool[N][N] qmap;
foreach (queen; queens) {
size_t qx = queen[0],
qy = queen[1];
qmap[qy][qx] = true;
}
writeln("Solution:");
N.iota.map!(x => (x + 1).to!string).array.reverse.each!((k) {
write(" ", k);
if (k.length < llen) {
write(" ".rep(llen - k.length));
}
});
writeln;
foreach (k, row; qmap) {
foreach (c; row) {
if (c) {
write("|Q" ~ padq);
} else {
write("|-" ~ pads);
}
}
writeln("| ", k+1);
}
"=".repeat.take(N*2 + 4).join.writeln;
} else {
foreach (j; N.iota) {
if (board[founds][j] is 0) {
queens[founds] = [j, founds];
changeBoard(j, founds, 1);
seqQueen(founds + 1);
changeBoard(j, founds, -1);
}
}
}
}
void main() {
seqQueen;
writeln(total);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment