Chinaunix首页 | 论坛 | 博客
  • 博客访问: 434629
  • 博文数量: 103
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 971
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-11 17:22
文章分类
文章存档

2008年(77)

2007年(26)

我的朋友

分类: C/C++

2008-04-25 12:57:38

queen[i]表示第i个皇后放在棋盘第i行的第queen[i]列上.

1.递归回溯:

#include <stdio.h>
#include <stdlib.h>

#define MAXQUEENS 100
int queen[MAXQUEENS + 1];
int n, num;

void backtrack(int t);
int safe(int k);
int main(int argc, char **argv)
{
        printf("Input queen numbers:");
        scanf("%d", &n);
        getchar();

        backtrack(1);

        return 0;
}

void backtrack(int t)
{
        int i;

        if(t > n){//found

                num++;
                printf("Output choice %d: \n", num);
                for(i = 1; i <= n; i++){
                        printf("%d ", queen[i]);
                }
                printf("\n");
        }
        else{
                for(i = 1; i <= n; i++){
                        queen[t] = i;
                        if(safe(t)){
                                backtrack(t + 1);
                        }
                }
        }
}

int safe(int k)
{
        int j, flag = 0;

        for(j = 1; j < k; j++){
                flag = (queen[k] == queen[j]) || ((j - queen[j]) == (k - queen[k])) || \
                        ((j + queen[j]) == (k + queen[k]));
                if(flag){
                        return 0;
                }
        }

        return 1;//safe

}


2.迭代回溯:

#include <stdio.h>
#include <stdlib.h>

#define MAXQUEENS 100
int queen[MAXQUEENS + 1];
int n, num;

int safe(int k);
int main(int argc, char argv)
{
        int i, k = 1;
      
        printf("Input queen numbers:");
        scanf("%d", &n);
        getchar();

        while(k > 0){
                queen[k] += 1;
                while((queen[k] <= n) && (!safe(k))){
                        queen[k] += 1;
                }
                if(queen[k] <= n){
                        if(k == n){
                                num++;
                                printf("Output choice %d: \n", num);
                                for(i = 1; i <= n; i++){
                                        printf("%d ", queen[i]);
                                }
                                printf("\n");
                        }
                        else{
                                k++;
                                queen[k] = 0;
                        }
                }
                else{
                        k--;
                }
        }

        return 0;
}

int safe(int k)
{
        int j, flag = 0;

        for(j = 1; j < k; j++){
                flag = (queen[k] == queen[j]) || ((j - queen[j]) == (k - queen[k])) || \
                        ((j + queen[j]) == (k + queen[k]));
                if(flag){
                        return 0;
                }
        }

        return 1;//safe

}

阅读(854) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~