#include #include #include #define MAXQUEENS 12 void printboard(int board[], int n) { int i = 0; for (i = 0; i < n; i++) { printf("(%d,%d)", i, board[i]); } printf("\n"); } int checkboard(int board[], int row) { int i = 0; for (i = 0; i < row; i++) { if (board[i] == board[row]) return 0; /* Same column. */ if( abs(board[i] - board[row]) == abs(i - row)) return 0; /* Same diagonal */ } return 1; } void solve(int board[], int row, int n) { int i = 0; /* Base case */ if (row == n) printboard(board, n); else { /* Recursive case. */ for (i = 0; i < n; i++) { board[row] = i; if (checkboard(board, row)) { solve(board, row + 1, n); } } } } int main() { int board[MAXQUEENS]; char c = 0; int n = 0; int pipefd[2]; pid_t childpid; while ((EOF != (c = getchar())) && (c != '\n')) { n = 10 * n + (c - '0'); } if (( n <= 0 ) || (n > MAXQUEENS)) { fprintf(stderr, "Lousy input\n"); } // Here is where we begin to depart from the traditional solution. if (pipe(pipefd) < 0) /* Create a pipe. */ { fprintf(stderr, "Pipe error!\n"); exit(-1); } childpid = fork(); /* fork another process */ if (childpid < 0) /* Forking error! */ { exit(-1); } else if (0 == childpid) /* Child process */ { close(pipefd[1]); /* Child closes write end of pipe. */ dup2(pipefd[0], STDIN_FILENO); /* Hook read end of pipe to stdin. */ close(pipefd[0]); /* Clean up duplicate descriptor. */ /* Replace the child process image with the "more" command. */ execlp("more", "more", NULL); /* Should never get past this line if execlp succeeded. */ } else /* Parent process */ { close(pipefd[0]); /* Parent closes read end of pipe. */ dup2(pipefd[1], STDOUT_FILENO); /* Hook write end of pipe to stdout. */ close(pipefd[1]); /* Clean up duplicate descriptor. */ solve(board, 0, n); /* Go solve the N-Queens problem. */ } }