HDU 2553 N皇后问题(经典的回溯问题)

来源:互联网 发布:fwt算法 编辑:程序博客网 时间:2024/05/16 08:01

我的这个把注释去掉就可以输出满足时的棋盘。

提前打表,不然会超时


#include<stdio.h>#include<string.h>int count;int n;int isExist(int i, int j, int (*Q)[11]) {  int s, t;  for (s = i, t = 0; t < n; t++) {    if (Q[s][t] && t != j) return 0;  }  for (s = 0, t = j; s < n; s++) {    if (Q[s][t] && s != i) return 0;  }  for (s = i-1, t = j-1; s >= 0 && t >= 0; s--, t--) {    if (Q[s][t]) return 0;  }  for (s = i-1, t = j+1; s >= 0 && t < n; s--, t++) {    if (Q[s][t]) return 0;  }  for (s = i+1, t = j-1; s < n && t >= 0; s++, t--) {    if (Q[s][t]) return 0;  }  return 1;}void Que (int j, int (*Q)[11]) {  int s, t;  if (j == n) {//    for (s = 0; s < n; s++) {//      for (t = 0; t < n; t++) {//        printf("%d ", Q[s][t]);//      }//      putchar('\n');//    }//    printf("\n");    count++;    return ;  }  for (s = 0; s < n; s++) {    if (isExist(s, j, Q)) {      Q[s][j] = 1;      Que(j+1, Q);      Q[s][j] = 0;    }  }}int main(void){  int Q[11][11], i, num[15];  for (i = 1; i < 11; i++) {    count = 0;    memset(Q, 0, sizeof(Q));    n = i;    Que(0, Q);    num[i] = count;  }  while (scanf("%d", &n) != EOF && n) {    printf("%d\n", num[n]);  }  return 0;}


原创粉丝点击