八皇后问题,上学的时候写的

#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
const int N = 8;

//把第n个皇后放在l列上是否冲突,隐含条件:第n个皇后肯定放在第n行上

bool test(int board[N][N], int n, int l)
{
    int i, j;
    for (i = 0; i < N; i++)
        if (board[n][i] == 1 || board[i][l] == 1)
            return false;
    //board[n][l]的对角线成员
    for (i = 0; i < N; i++)
        for (j = 0; j < N; j++)
            if ((n - l) == (i - j) || (i + j == n + l))
                if (board[i][j] == 1)
                    return false;
    return true;
}

void put(int board[N][N], int n, int l)
{
    board[n][l] = 1;
}

void show(int board[N][N])
{
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
            cout << board[i][j] << ' ';
        cout << endl;
    }
    cout << endl;
}

void solve(int board[N][N], int n)
{
    int i, j;
    static int count = 0;
    if (n == N)
    {
        count++;
        cout << "以下是第" << count << "种可行放法" << endl;
        show(board);
        return;
    }
    for (i = 0; i < N; i++)
    {
        if (test(board, n, i))
        {
            put(board, n, i);
            solve(board, n + 1);
            board[n][i] = 0; //backtrace
        }
    }
}

int main()
{
    int board[N][N];
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
            board[i][j] = 0;
    }
    solve(board, 0);
    return 0;
}

  

    原文作者:八皇后问题
    原文地址: https://www.cnblogs.com/jimichen/p/3926045.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞