/* Generates all possible placements of n non-attacking rooks on an nxn board. In other words, all permutations of 1 .. n. */ #include #include #define MAX 12 int n; int A[MAX]; int sol[MAX]; void Print() { int i; for (i=0; i < n; i ++) printf(" %2d", sol[i] + 1); printf("\n"); } void Rook(int col) { int row; for (row=0; row < n; row ++) { if (A[row]) { sol[col] = row; A[row] = 0; if (col < n-1) Rook(col+1); else Print(); A[row] = 1; } } } int main(int argc, char *argv[]) { int i; if (argc != 2) { printf("\n A single argument expected.\n"); return 1; } n = atoi(argv[1]); if (n < 0) { printf("\n Positive number expected.\n"); return 2; } if (n > MAX) { printf("\n Number not greater than %d expected.\n", MAX); return 3; } for (i=0; i < n; i ++) A[i] = 1; Rook(0); return 0; }