C++ 8个皇后拼图,用户输入c++;

C++ 8个皇后拼图,用户输入c++;,c++,visual-studio-2013,n-queens,C++,Visual Studio 2013,N Queens,我正在研究8皇后之谜,我写下了我的代码版本,解决了第一个皇后总是放在第0行的问题 #include "stdafx.h" #include <iostream> using namespace std; const int NUMBER_OF_QUEENS = 8; // Constant: eight queens int queens[NUMBER_OF_QUEENS]; // Check whether a queen can be placed at row i and

我正在研究8皇后之谜,我写下了我的代码版本,解决了第一个皇后总是放在第0行的问题

#include "stdafx.h"
#include <iostream>
using namespace std;


const int NUMBER_OF_QUEENS = 8; // Constant: eight queens
int queens[NUMBER_OF_QUEENS];
// Check whether a queen can be placed at row i and column j
bool isValid(int row, int column)
{
    for (int i = 1; i <= row; i++)
    if (queens[row - i] == column // Check column
        || queens[row - i] == column - i // Check upper left diagonal
        || queens[row - i] == column + i) // Check upper right diagonal
        return false; // There is a conflict
    return true; // No conflict
}
// Display the chessboard with eight queens
void printResult()
{
    cout << "\n---------------------------------\n";
    for (int row = 0; row < NUMBER_OF_QUEENS; row++)
    {
        for (int column = 0; column < NUMBER_OF_QUEENS; column++)
            printf(column == queens[row] ? "| Q " : "| ");
        cout << "|\n---------------------------------\n";
    }
}
// Search to place a queen at the specified row
bool search(int row)
{
    if (row == NUMBER_OF_QUEENS) // Stopping condition
        return true; // A solution found to place 8 queens in 8 rows
    for (int column = 0; column < NUMBER_OF_QUEENS; column++)
    {
        queens[row] = column; // Place a queen at (row, column)
        if (isValid(row, column) && search(row + 1))
            return true; // Found, thus return true to exit for loop
    }
    // No solution for a queen placed at any column of this row
    return false;
}
int main()
{
    search(0); // Start search from row 0. Note row indices are 0 to 7
    printResult(); // Display result
    return 0;
}
#包括“stdafx.h”
#包括
使用名称空间std;
常数整数皇后数=8;//常数:八皇后
int皇后[皇后的数目];
//检查第一行和第j列是否可以放置皇后
bool是有效的(int行,int列)
{

对于(inti=1;i而言,问题在于代码中缺少分号

cout << "Enter a row number from 0-7"; // here

cout啊。我的错。我会编辑它。但是我的问题仍然存在。我没有得到应该得到的正确布尔值。为什么需要
搜索(0);
搜索(行)之后
。此外,您的
isValid
方法接受两个参数,即一行和一列。好的,所以我再次编辑了它。现在我将行和列传递给isValid。但是,除0之外输入的每个值都返回0或false。我如何从逻辑上解决此问题?嘿…您的程序绝对正确…问题在于您的输入…您给出了一个co更正行和列,您将获得所需的输出。在这里…我使用了
row=2
column=5
,并且我在输出中得到了正确的结果。请不要编辑您的问题,以合并解决问题的代码。这会使答案无效,使问题更难解决。一旦您找到问题的答案(例如,你的代码无法编译)你应该接受解决问题的答案,对任何你认为有用的答案都可以随意投票,然后继续。如果你仍然有问题,在做了研究之后,如果你仍然卡住了,你应该问另一个问题。
cout << "Enter a row number from 0-7"; // here