How to resolve the algorithm N-queens problem step by step in the Processing programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm N-queens problem step by step in the Processing programming language
Table of Contents
Problem Statement
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size NxN. For the number of solutions for small values of N, see OEIS: A000170.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm N-queens problem step by step in the Processing programming language
Source code in the processing programming language
int n = 8;
int[] b = new int[n];
int s = 0;
int y = 0;
void setup() {
size(400, 400);
textAlign(CENTER, CENTER);
textFont(createFont("DejaVu Sans", 44));
b[0] = -1;
}
void draw() {
if (y >= 0) {
do {
b[y]++;
} while ((b[y] < n) && unsafe(y));
if (b[y] < n) {
if (y < (n-1)) {
b[++y] = -1;
} else {
drawBoard();
}
} else {
y--;
}
} else {
textSize(18);
text("Press any key to restart", width / 2, height - 20);
}
}
boolean unsafe(int y) {
int x = b[y];
for (int i = 1; i <= y; i++) {
int t = b[y - i];
if (t == x ||
t == x - i ||
t == x + i) {
return true;
}
}
return false;
}
void drawBoard() {
float w = width / n;
for (int y = 0; y < n; y++) {
for (int x = 0; x < n; x++) {
fill(255 * ((x + y) % 2));
square(x * w, y * w, w);
if (b[y] == x) {
fill(255 - 255 * ((x + y) % 2));
textSize(42);
text("♕", w / 2 + x *w, w /2 + y * w);
}
}
}
fill(255, 0, 0);
textSize(18);
text("Solution " + (++s), width / 2, height / 90);
}
void keyPressed() {
b = new int[n];
s = 0;
y = 0;
b[0] = -1;
}
from itertools import permutations, product
n = 8
cols = range(n)
i = 0 # solution shown
solutions = [vec for vec in permutations(cols)
if n == len(set(vec[i] + i for i in cols))
== len(set(vec[i] - i for i in cols))]
def setup():
size(400, 400)
textAlign(CENTER, CENTER)
textFont(createFont("DejaVu Sans", 44))
def draw():
background(0)
w = width / n
for x, y in product(range(n), range(n)):
fill(255 * ((x + y) % 2))
square(x * w, y * w, w)
if solutions[i][y] == x:
fill(255 - 255 * ((x + y) % 2))
text(u'♕', w / 2 + x * w, w / 3 + y * w)
def keyPressed(): # show next solution
global i
i = (i + 1) % len(solutions)
You may also check:How to resolve the algorithm Langton's ant step by step in the Processing programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the Processing programming language
You may also check:How to resolve the algorithm Greyscale bars/Display step by step in the Processing programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the Processing programming language
You may also check:How to resolve the algorithm Classes step by step in the Processing programming language