这回不会爆栈了,但是效率很低,O(n^2)的时间复杂度,需要优化
#include <stdio.h> #define N 10 int q[N+1] = {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 next_qn() { int i=0; while (i <= N) { if (q[i] < N-1) { q[i] +=1; break; } q[i] = 0; i++; } return; } int main(int argc, char* argv[]) { while (q[N] == 0) { int i; for (i=0; i<N; i++) { if (!can_put(i, q[i])) break; } if (i == N) { cnt++; print_q(); } next_qn(); } printf("CNT: %d\n", cnt); return 0; }
时间: 2024-11-05 06:25:50