八个皇后二维阵列,带有gotos errror
Eight Queens 2-dimensional array with gotos errror
我正在处理带有二维数组的八个皇后问题,当我尝试运行代码时,它给了我细分错误,我似乎无法弄清楚为什么。八个皇后难题是将八个国际象棋皇后放在8x8棋盘上的问题,这样没有两个皇后互相威胁。因此,解决方案要求没有两个皇后共享相同的行,列或对角线。
#include <iostream>
using namespace std;
void print(int b[][8]);
int main()
{
int b[8][8]={0},
r,
c=0;
b[0][0]=1; //putting 1st queen piece on the upper left corner
/*column section*/
next_col:
++c; //advance column position
if(c==8) //if solutions for columns0-7 are found then print
goto print;
r = -1; //if not, start at the top of the column
/*row section*/
next_row:
++r;
if(r==8)
goto backtrack;
for(int i=0; i<c; ++i)
if(b[r][i] == 1)
goto next_row;
for(int i=1; (r-i)>=0 && (c-i)>=0; ++i)
if(b[r-i][c-i]==1) //if conflict found in updiagonals
goto next_row;
for(int i=1; (r+i)<8 && (c-i)>=0; ++i)
if(b[r+i][c-i] ==1) //if conflict found in down diagonal try next row
goto next_row;
else
b[r][c]=1; //no conflicts found, so place queen & move to next col
goto next_col;
/*backtrack section*/
backtrack:
--c; //go back one column
if(c== -1) // if past first column, all solutions found so terminate prog
return 0;
r = 0; //start looking from first row
while(b[r][c]!=1) // while we haven't found the queen
++r; //move to next row of current column
b[r][c]=0; //remove queen piece
goto next_row;
/*print section*/
print:
print(b); // print the board
goto backtrack;
}
void print(int b[][8])
{
for(int i=0; i<8; i++)
{
for(int j=0; j<8; j++)
cout << b[i][j] << " ";
cout << endl;
}
}
在第三循环中,您检查下对角线,如果一个对角线正方形,则有其他会导致女王放置女王,而您想要它只有在所有对角线正方形都没有占用时才放置。卸下其他,并且可以正常工作(至少在我的机器上可以做)。
相关文章:
- OpenMP阵列性能较差
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- 当我的阵列太大时出现分段错误
- 位阵列上的快速AND运算
- 阵列必须使用大括号封闭的初始器进行初始化
- 没有从阵列<float>到阵列<int>的可行转换
- C++动态安全 2D 交错阵列
- 将平面阵列重塑为复杂的特征类型
- 如何使用英特尔 PIN 捕获阵列的所有负载?
- 为什么我能够为阵列分配比计算机实际拥有的内存更多的内存
- 库特<<恩德尔;不适用于打印 2D 阵列
- 数组类 阵列的打印输出
- 从较小的阵列到较大的阵列的元素级转换
- 仅在大型阵列上出现合并排序分段错误
- 从阵列C++中删除重复项
- 阵列的大小在C++中是否灵活?
- 反转阵列中的正序列
- 具有可变尺寸的 C++ 2D 阵列
- 二维阵列的动态分配
- 八个皇后二维阵列,带有gotos errror