2015-12-03 71 views
-1

我正在研究的8個皇后之謎,我寫下了我的版本的代碼,解決了第一女王總是擺出一排問題08皇后問題與用戶輸入的C++

#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; 
} 

現在我想修改它,以便它將採取用戶輸入,因此它可以從0-7行開始。 我已經把這樣的事情在主函數

int row, col = 0; 
cout << "Enter a row number from 0-7 "; 
cin >> row; 
search(row);// Start search from row 0. Note row indices are 0 to 7 
bool yas = isValid(row, col); 
cout << yas; 
printResult(); // Display result 
return 0; 

然而,當我運行它,我不斷收到一個語法錯誤或虛假不管。有沒有更好的方式來接受用戶輸入或者我邏輯上做錯了?

+2

請從編輯你的問題納入能解決你的問題,不要代碼。它使答案無效,並使解決問題變得更加困難。一旦你有了你的問題的答案(例如你的代碼不能編譯),你應該接受解決問題的答案,隨時提供你認爲有用的答案,然後繼續。如果你仍然有問題,在做了研究後,如果你仍然卡住,你應該問另一個問題。 – Tas

回答

0

問題是你在你的代碼錯過了分號...

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

啊。我的錯。我會編輯它。我的問題依然存在。我沒有得到正確的布爾值,我應該。 –

+0

爲什麼在搜索(行)之後需要'search(0);''。而且,你的'isValid'方法接受兩個參數即一行和一列。 –

+0

好的,我再次編輯它。現在我已經將行和列傳遞給了isValid。但是,除0以外的每個輸入值都返回0或false。我怎樣才能在邏輯上解決這個問題? –