八皇后实现总结

问题描述

n*n的棋盘上放n个皇后

源码

#include<iostream>
using namespace std;
/*eight queens*/
int solutions = 0;
void printResults(int queens[], int n)
{
    int i, j;
    for (i = 0; i < n; i++)
    {
        for (j = 0; j < n; j++)
            cout << (j == queens[i] ? "1" : "o")<<" ";
        cout << endl;
    }
}
void tryRow(int queens[],int n,int row)  //前0~row-1行都放好的情况下,找第i行能放皇后的列
{
    int i,ok=1;
    for (int j = 0; j < n; j++)
    {
        ok = 1;    //don't forget this line!!!!
        //cout << row << endl;
        //判断是否此处是否与0~i-1行冲突,若冲突则直接进入下一个
        for (i = 0; i < row; i++)
            if ((queens[i] == j) || (i - row == queens[i] - j) || (i - row == j - queens[i]))
            {
                ok = 0;
                //cout << "row = " << row << "  j = " << j << "  not ok" << endl;
            }
        
        if (ok)
        {
            queens[row] = j;
            if (row == n-1) //have finished putting the last queen,print the result
            {//////////////////////right here bro!!!!!n-1 rather than n!!!
                solutions++;
                cout << endl << "----------------"<<endl ;
                printResults(queens, n);
            }
            else        //put the next queen
            {
                tryRow(queens, n, row + 1);
            }
        }
    }
}

int main()  //n*n的棋盘上摆n个皇后,任意两个不能同行同列或同斜线
{
    int n = 8;
    int *queens = new int[n];  //a的下标范围是0~n-1
    tryRow(queens, 8, 0);

    cout <<endl<< solutions;

    delete[] queens;
    while (1);
    return 0;
}

一些小坑

1. 忘了一处初始化:

for循环开始后,对每个j,先ok=1;

2 条件边界值写错,

应为 i == n -1 而不是i == n ,即行号范围是0~n-1,第n-1行填满即可输出

转载于:https://www.cnblogs.com/YuQiao0303/p/9621246.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值