Chinaunix首页 | 论坛 | 博客
  • 博客访问: 136508
  • 博文数量: 75
  • 博客积分: 3483
  • 博客等级: 中校
  • 技术积分: 820
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-07 08:31
文章分类

全部博文(75)

文章存档

2011年(53)

2010年(22)

我的朋友

分类:

2010-12-22 20:33:18

Just for learning..
 
It can print only one selection for eight queen
 
 

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

#define SIZE 8

void printqueen(int arr[][SIZE]);
int queen(int x, int y);
int lost(int x, int y);

static int arr[8][8] = {
                    {0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,0,0},
                    {0,0,0,0,0,0,0,0}
                    };
char buf[1024];
int main(void){
    printqueen(arr);
    lost(0,0);
    //printqueen(arr);

    return 0;
}



void printqueen(int arr[][SIZE]){
    int a, b;
    for(a = 0;a < SIZE;a++)
    {
        for(b = 0; b < SIZE; b++)
        {
            if(arr[a][b] != 0)
                printf("* ");
            else
                printf(". ");
        }
        putchar('\n');
    }
    puts("-----------------\n");
}

//if can be falldown, return 1, else return 0

int queen(int x, int y){
    int i, j;
    for(i = 0; i < SIZE; i++)
    {
        if(i == x) continue;
        if(arr[i][y] == 1) return 0;
    }

    for(j = 0; j < SIZE; j++)
    {
        if(j == y) continue;
        if(arr[x][j] == 1) return 0;
    }

    for(i = 0; i < SIZE; i++)
        for(j = 0; j < SIZE; j++)
        {
            if(i == x && j == y) continue;
            if( ((x + y) == (i + j)) || ((y - x) == (j - i)) ){
                if(arr[i][j] == 1) return 0;
            }
        }

    return 1;
}

int lost(int x, int y){
    int i;
    if(( x == 7 && queen(x, y))||( y == 7 && queen(x, y)))
    {
        arr[x][y] = 1;
        printqueen(arr);
        //return 1;

    }
    
    for(i = 0; i < SIZE; i++)
    {
        if(queen(x, i))
        {
            arr[x][i] = 1;
            if(!lost(x+1, 0))
            {
                arr[x][i] = 0;
                continue;
            }
            return 1;
        }
    }
    return 0;
}


阅读(307) | 评论(0) | 转发(0) |
0

上一篇:happyness 2

下一篇:my code 20101220_5

给主人留下些什么吧!~~