#include <stdlib.h> #include <stdio.h>
#define SIZE 8
void printqueen(int arr[][SIZE]); int queen(int x, int y); int lost(int x, int y);
static int arr[8][8] = { {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0} };
int main(void){ printqueen(arr); lost(0,0); printqueen(arr); return 0; }
void printqueen(int arr[][SIZE]){ int a, b; for(a = 0;a < SIZE;a++) { for(b = 0; b < SIZE; b++) { if(arr[a][b] != 0) printf("* "); else printf(". "); } putchar('\n'); } puts("-----------------\n"); }
//if can be falldown, return 1, else return 0
int queen(int x, int y){ int i, j; for(i = 0; i < SIZE; i++) { if(i == x) continue; if(arr[i][y] == 1) return 0; }
for(j = 0; j < SIZE; j++) { if(j == y) continue; if(arr[x][j] == 1) return 0; }
for(i = 0; i < SIZE; i++) for(j = 0; j < SIZE; j++) { if(i == x && j == y) continue; if( ((x + y) == (i + j)) || ((y - x) == (j - i)) ){ if(arr[i][j] == 1) return 0; } } return 1; }
int lost(int x, int y){ int xx, yy; //printf("--%d--%d--\n", x, y);
if(y > SIZE) return 0; for(xx = x; xx < SIZE; xx++) { yy = y; if(queen(xx, yy)) { arr[xx][yy] = 1; if(lost(++xx, 0)) arr[xx][yy] = 1; else lost(xx, ++yy);
return 1; } return 0; } return 0; }
|