n皇后

#include <stdio.h>
#define N 4

enum bool {TRUE, FALSE};

void print_Q(int *Q)
{
    int i;
    for (i = 1; i <= N; i++)
        printf("%d, ", Q[i]);
    printf("\n");
}


void RecursiveNQueens(int *Q, int r)
{
    if (r == N+1)
        print_Q(Q);
    else {
        int j, i;
        enum bool legal;
        for (j = 1; j <= N; j++) {
            legal = TRUE;
            for (i = 1; i <= r-1; i++) {
                if ( (Q[i] == j) || (Q[i] == j+r-i) || (Q[i] == j-r+i) )
                    legal = FALSE;
            }
            if (legal == TRUE) {
                Q[r] = j;
                //printf("Q[%d] = %d\n", r, j);
                RecursiveNQueens(Q, r+1);
            }
        }
    }
}

int main()
{
    int Q[N+1] = {0};
    int r = 1;
    RecursiveNQueens(Q, r);
    return 0;
}

 

上一篇:abc225E.フ/7


下一篇:leetcode205.同构字符串