基本上,我必須編寫一個基本程序來解決我已經完成的n皇后問題,但是如果輸入任何數字> = 11,它會引發分段錯誤。在遞歸n皇后程序中獲取C++分割錯誤
從我在線閱讀的內容來看,這個錯誤通常是由處理內存時錯誤的邏輯引起的,但我似乎無法弄清楚我做錯了什麼。
void generateBoard(int board[],int column,int length,int count)
{
if(column == 0 && board[0]<length) //prevents outputting the results infinitely
{
++board[0];
generateBoard(board, ++column, length, count);
}
else
{
bool lineNotFound = true;
int row = board[column];
while(lineNotFound && row < length)
{
++row; //temporary value for a column value candidate
lineNotFound = false;
for(int i = 0; i < column && !lineNotFound; ++i)
{
if(board[i] == row || (board[i]+column-i) == row || (board[i]-column+i) == row) // check diagonal and horizontal
{
lineNotFound = true;
}
else
{
board[column] = row;
}
}
}
if(column == length-1 && !lineNotFound) // at last column and valid board
{
output(board,length,++count);
generateBoard(board,column,length,count);
}
else if(!lineNotFound) // not at last column, but valid position found
{
generateBoard(board,++column,length,count);
}
else if(column != 0) //no valid columns, go back a step
{
board[column] = 0;
generateBoard(board,--column,length,count);
}
}
}
我意識到是代碼一大塊,但我覺得有必要將它張貼所有獲得問題的想法。
任何想法? :s
我是新來的編程C++,所以我不知道從哪裏開始調試。
你能寫出你用來調用引起分段錯誤的函數的參數的值嗎? –
「我是編程C++的新手,所以我不知道從哪裏開始調試。」開始在調試器下運行你的程序!有了這個,你可以找出哪條線爆炸。這應該提供一些信息來弄清楚出了什麼問題。 –
int board [boardSize]; 填充(board,board + boardSize,0); generateBoard(board,0,boardSize,0);因此,在這種情況下,generateBoard(board,0,11,0); –