NQueens使用堆栈的问题,代码给出了错误的输出

问题描述

我已经用下面的代码解决了著名的NQueens问题。但是,这里的问题是它只能解决7号或更小的尺寸的板子,我需要在11x11尺寸的板子上工作。假定isPlaceValid()函数正常工作,并且int colIndex参数始终传递的值为0。有人有什么建议吗?我没有遇到任何堆栈溢出或分段错误问题,我的代码只是决定退出我的函数

bool Queensproblem::setQueens(int colIndex)
{
    std::stack<class Pair> recurStack; //initialize the stack
    Pair init,stacktop,to_push; //we have 3 different Pair objects
    init.row = 0; //initial row in set to 0
    init.col = colIndex; //initial column is set to 0
    recurStack.push(init); // push this pair onto the stack
    
  
  while((recurStack.top().col) < numOfQueens){ // once the the item at the top of the stack has col = to the number of queens,we are done!
    stacktop = recurStack.top(); //stacktop is keeping track of the current colIndex
    recurStack.pop(); //we put the object with the incremented col index on the top and get rid of it,theoretically leaving on the correct queen locations
    if(stacktop.row == numOfQueens){ //we have run out of inital rows to attempt
      return false; //basically we've backtracked numOfQueens times and there are no valid combinations left to try
    }
    for(int rowIndex = 0; rowIndex < numOfQueens; rowIndex++){ //we want to iterate through each row on the board for the current col index
      
      if(isPlaceValid(rowIndex,stacktop.col)){ //if the queen would not be in danger here
        chesstable[rowIndex][stacktop.col] = 1; //set that location = to 1
        to_push.row = rowIndex; 
        to_push.col = stacktop.col;
        recurStack.push(to_push); //version of to_push with the location of our set queen is pushed
        to_push.coL++;
        recurStack.push(to_push);//increment col and push to_push again so that stacktop can start at the next column
        break;
      }
      else if(rowIndex == (numOfQueens - 1)){ //this means we've reached the bottom of the board and no place was valid
        chesstable[rowIndex][stacktop.col] = 0; //set that spot = to 0 still
        to_push = recurStack.top(); //to_push is equal to the most recent valid location
        recurStack.pop(); //remove that most recent location because we're backtracking
        if(to_push.col == 0) //we are at the bottom of the stack
        {
          to_push.row += 1;
          recurStack.push(to_push); //increment the initial rowIndex of our starting queen,and start from scratch
        }
        else{
          rowIndex = to_push.row + 1;
          continue;
        }
      }
      else{
        chesstable[rowIndex][stacktop.col] = 0;
      }
    }
  }
  
  return true;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)