#include #include int board[8][8]; void printBoard() { int row,col; for(row=0; row<8; row++) { for(col=0; col<8; col++) printf("%2d", board[row][col]); printf("\n"); } printf("\n"); } int check(int row, int col) { int i, j; for(i=0; i<8; i++) if(board[i][col] == 1) return 0; for(j=0; j<8; j++) if(board[row][j] == 1) return 0; for(i=row, j=col; i>=0 && j>=0; i--, j--) if(board[i][j] == 1) return 0; for(i=row, j=col; i<8 && j>=0; i++, j--) if(board[i][j] == 1) return 0; return 1; } int solve(int col) { if(col == 8) return 1; for(int row=0; row<8; row++) { if(check(row, col) == 1) { board[row][col] = 1; // place a queen //printBoard(); // uncomment this line to see the intermediary attempts if(solve(col+1) == 1) return 1; board[row][col] = 0; // undo that move } } return 0; // if none of the rows worked return 0 } int main() { int row, col; for(row=0; row<8; row++) for(col=0; col<8; col++) board[row][col]=0; // clear the board if(solve(0) == 1) printBoard(); else printf("Could not find a solution.\n"); system("pause"); }