Among millions of chess problems there is one given by French army captain Henri Delannoy at about 1880. The goal is counting the different ways a king can move from one corner to the opposite one on an empty chess board. This problem has been solved for chess boards of any size. This is to simulate all the ways, showing them on a TFT display, and counting them.
Two different recursive algorithms are given. The first one:
void Walk(byte x, byte y) {
if (x > xMax) return;
if (y > yMax) return;
draw(x, y, king);
for (int i = -1; i <= 1; i++) {
byte xDest = x + (i >= 0);
byte yDest = y + (i <= 0);
if (xDest <= xMax || yDest <= yMax)
Walk(xDest, yDest);
else {
print(++nr);
dt = analogRead(readDt);
delay(dt);
}
}
draw(x, y, field);
}
and the second one:
void Walk(int x, int y, int i) {
/*
i=-1: senkrecht nach oben
i= 0: nach schraeg oben rechts
i= 1: waagerecht nach rechts
berechne Zielkoordinaten:
*/
x = x + (i >= 0);
y = y + (i <= 0);
// pruefe, ob Brettrand ueberschritten:
if (x > xMax) return;
if (y > yMax) return;
// nein, alles o.k.
draw(x, y, king);
if (x == xMax && y == yMax) {
// Ziel erreicht
print(++nr);
dt = analogRead(readDt);
delay(dt);
}
else
// mache weiter:
for (int i = -1; i <= 1; i++) Walk(x, y, i);
draw(x, y, field);
}
The complete code is attached in the ZIP file.
Both versions can be delayed by using a potentiometer, otherwise you see nothing. The actual size is shown in the lower left corner. Next to it is the counter of ways executed.
To enable you to see the simulation of boards of different sizes, at each press of the RESET button the size is incremented up to 8 and then begins with 3 again.
Comments