#include <stdio.h> #define N 9 int q[N] = {0}; int cnt = 0; void print_q() { int i; for (i=0; i<N; i++) printf("%d ", q[i]); printf("\n"); return; } int can_put(int m, int n) { int i,j; //row is ok //colume for (i=0; i<m; i++) { if (q[i] == n) return 0; } //left-up for (i=m-1,j=n-1; i>=0 && j>=0; i--,j--) { if (q[i] == j) return 0; } //right-up for (i=m-1,j=n+1; i>=0 && j<N; i--,j++) { if (q[i] == j) return 0; } return 1; } void put_q(int m, int n) { if (m == 0 && n >= N) { printf("CNT: %d\n", cnt); } else if (m >= N) { print_q(); cnt++; put_q(m-1, q[m-1]+1); } else if (n >= N) { put_q(m-1, q[m-1]+1); } else if (can_put(m, n)) { q[m] = n; put_q(m+1, 0); } else { put_q(m, n+1); } return; } int main(int argc, char* argv[]) { put_q(0, 0); return 0; }
时间: 2024-11-10 00:07:16