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

全部博文(75)

文章存档

2011年(53)

2010年(22)

我的朋友

分类:

2010-12-20 21:49:32

Just for learning...
 
 

#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}
                    };

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 xx, yy;
    //printf("--%d--%d--\n", x, y);

    if(y > SIZE) return 0;
    for(xx = x; xx < SIZE; xx++)
    {
        yy = y;
        if(queen(xx, yy))
        {
            arr[xx][yy] = 1;
            if(lost(++xx, 0))
                arr[xx][yy] = 1;
            else
                lost(xx, ++yy);

            return 1;
        }
        return 0;
    }
    return 0;
}


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

上一篇:my code 20101220

下一篇:my code 20101220_3

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