1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <stdio.h>
#include <stdlib.h>
typedef struct {
unsigned short *plateau;
size_t cote;
} t_echiquier;
unsigned short valideDroite(t_echiquier *e, unsigned short l, unsigned short c, char sens) {
unsigned short i;
for (i=0; i < e->cote; i++) {
switch (sens) {
case 'c': // Colonne
if (i == c) continue;
if (e->plateau[l*e->cote + i] != 0) return 0;
break;
case 'l': // Ligne
if (i == l) continue;
if (e->plateau[i*e->cote + c] != 0) return 0;
break;
case 'd': // Diagonale
if (i == 0) continue;
if ((short)(l - i) >= 0 && (short)(c - i) >= 0 && e->plateau[(l-i)*e->cote + (c-i)] != 0) return 0;
if ((short)(l - i) >= 0 && (short)(c + i) < e->cote && e->plateau[(l-i)*e->cote + (c+i)] != 0) return 0;
if ((short)(l + i) < e->cote && (short)(c - i) >= 0 && e->plateau[(l+i)*e->cote + (c-i)] != 0) return 0;
if ((short)(l + i) < e->cote && (short)(c + i) < e->cote && e->plateau[(l+i)*e->cote + (c+i)] != 0) return 0;
break;
default:
return 0;
}
}
return 1;
}
unsigned short validePosition(t_echiquier *e, unsigned short l, unsigned short c) {
if (valideDroite(e, l, c, 'l') == 0) return 0;
if (valideDroite(e, l, c, 'c') == 0) return 0;
if (valideDroite(e, l, c, 'd') == 0) return 0;
return 1;
}
void afficheEchiquier(t_echiquier *e) {
unsigned short l;
unsigned short c;
for (l=0; l < e->cote; l++) {
for (c=0; c < e->cote; c++) {
printf("%c", e->plateau[l*e->cote + c] == 0 ?'.' :'D');
}
fputc('\n', stdout);
}
fputc('\n', stdout);
}
unsigned long placeDame(t_echiquier *e, unsigned short l, unsigned long cpt) {
unsigned short c;
for (c=0; c < e->cote; c++) {
e->plateau[l*e->cote + c]=1;
if (validePosition(e, l, c) != 0) {
if (l < (e->cote-1))
cpt=placeDame(e, l+1, cpt);
else {
afficheEchiquier(e);
cpt++;
}
}
e->plateau[l*e->cote + c]=0;
}
return cpt;
}
int main(int argc, char *argv[]) {
t_echiquier e;
e.cote=atoi(argv[1]);
e.plateau=calloc(e.cote * e.cote, sizeof(*e.plateau));
printf("%hu => %lu\n", e.cote, placeDame(&e, 0, 0));
free(e.plateau);
} |
Partager