我应该将一个排列程序转换为8个皇后程序。该程序应该在第一行中放下一个女王,然后在第二行中它应该放置一个不在前一个女王的直接视图中的女王。最后,如果无法放置8个皇后,程序将拿起前一个皇后并重新计算。
该程序的输出如下。
执行程序......
$demo
Q _ _ _ _ _ _ _
_ _ _ _ _ _ _ Q
_ _ _ _ _ _ Q _
_ _ _ _ _ _ _ Q
_ _ _ _ _ _ Q _
_ _ _ _ _ _ _ Q
_ _ _ _ _ _ Q _
_ _ _ _ _ _ _ Q
(它是8x8)
显然,最后两行是彼此直接看到的,我不确定我应该从哪里开始修复这个,如果我能得到很好的输入,希望它不是明显的东西!
代码:
#include<iostream>
#include<iomanip>
#include<limits>
using namespace std;
char BOARD[8][8];
void clearBoard();
void attempt(int n, int row, int column);
void placeQueen(int row, int column);
void removeQueen(int row, int column);
bool currentPathSuccess(int n, int row, int column);
bool currentPathStillViable(int row, int column);
void printBoard(int n);
int main()
{
int n = 8;
clearBoard();
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
attempt(n, i, j);
}
}
printBoard(n);
return 0;
}//end Main
void clearBoard()
{
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < 8; j++)
{
BOARD[i][j] = '_';
}
}
}//end clearBoard Function
void attempt(int n, int row, int column)
{
placeQueen(row, column);
if(currentPathSuccess(n, row, column))
{printBoard(n);}
else
currentPathStillViable(row, column);
}// end attempt Function
void placeQueen(int row, int column)
{
BOARD[row][column] = 'Q';
}
void removeQueen(int row, int column)
{
BOARD[row][column] = '_';
}//end placeQueen Function
bool currentPathSuccess(int n, int row, int column) //Flag
{
bool success = true;
if((n > column)||(n > row))
{
success = false;
}
return success;
}//end currentPathSuccess Function
bool currentPathStillViable(int row, int column) //Flag
{
bool viable = true;
int flag = 0;
for(int x = 0; x < 8; x++)
{
if(BOARD[row][x] == 'Q')
{
flag++;
}
}
if(flag > 1)
{
removeQueen(row, column);
placeQueen(row + 1, column);
}
return viable;
}// end currentPathStillViable
void printBoard(int n)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
cout << BOARD[i][j] << " ";
}
cout << endl;
}
cout << endl;
}//end printBoard Function