问题描述
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行填满即可输出