八皇后

#define _CRT_SECURE_N0_WARNINGS 1
#include
#define N 8
//八皇后问题
char board[N + 2][N + 2];
int counter = 0;

void init(void)
{
    //初始化边界
    for (int row = 0; row < N + 2; row++){
        for (int col = 0; col < N + 2; col++){
            board[0][col] = '#';
            board[N + 1][col] = '#';
            board[row][0] = '#';
            board[row][N + 1] = '#';
        }
    }
    //初始化内部
    for (int i = 1; i <= N; i++)
    {
        for (int j = 1; j <= N; j++){
            board[i][j] = ' ';
        }
    }
}

//显示棋盘
void show(void)
{
    for (int i = 0; i < N + 2; i++)
    {
        for (int j = 0; j < N + 2; j++)
        {
            printf("%c ",board[i][j]);
        }
        printf("\n");
    }
}

//相对于当前位置的偏移量
struct Pos{
    int ros; //行偏移量
    int cos;//列偏移量
};
struct Pos pos[3] = { { -1, -1 }, { -1, 0 }, {-1,1} };


//测试row行col列是否可以摆放皇后
int check(int row, int col)
{
    int new_row, new_col;
    int ret = 1;
    for (int i = 0; i < 3 && ret; i++)
    {
        new_row = row;
        new_col = col;
        while (ret&&board[new_row][new_col] != '#')
        {
            if (board[new_row][new_col] == '*')
            {
                ret = 0;
                break;
            }
            new_row = new_row + pos[i].ros;
            new_col = new_col + pos[i].cos;
        }
    }
    return ret;
}
//找合适位置摆放皇后
//回溯算法
void find(int row)
{
    if (row > N)
    {
        show();
        counter++;
        printf("%d\n",counter);
    }
    else
    {
        for (int col = 1; col <= N; col++)
        {
            if (check(row, col))
            {
                board[row][col] = '*';
                find(row + 1);
                board[row][col] = ' ';
            }
        }
    }

}

int main()
{
    init();
    find(1); //从第一行开始找
    return 0;
}

运行结果(92种):
八皇后_第1张图片
八皇后.png

你可能感兴趣的:(八皇后)