so, have assignment need solve n-queens* problem using stack.
*n-queens problem: have chessboard n rows/columns/queens. must place each queen cannot attack of others on board.
i created queen class store row , column positions each valid queen placed, , working fine. far can tell, of sorting , checking logic fine. however, either in main or solve function, i'm getting segmentation fault, when debug. when ran normally, exits. debugger unfortunately doesn't let me go line line, i've manually done , still can't figure out.
void solve(int k, int n) { stack<queen> queenstack; if(k == n) { while(!queenstack.empty()) { cout << queenstack.top().rowpos << ", " << queenstack.top().colpos << endl; queenstack.pop(); }//end while }//endif else { (int = 0;i < n; i++) { if (issafe(k,i)) { queen queen(k,i); queenstack.push(queen); solve(k++,n); }//end if else { if(queenstack.empty()) { break; }//end if else { queenstack.pop(); k--; }//end else }//end else }//end }//end else }//end void
then main:
int main() { int n = 0; cout << "please pick integer 3 or greater , less whatever think won't crash computer." << endl; cin >> n; while (n < 3) { cout << "please pick integer 3 or greater , less whatever think won't crash computer." << endl; cin >> n; }//end while solve(0,n); return 0; }//end main
my ifsafe bool function checks based on row, pass in int, , return true/false loop.
first of all, there's obvious issue in code lead stack overrun. way recursively call solve function:
solve(k++,n);
will first call solve
, , increment k
. solve(0, n)
calls solve(0, n)
, in turn calls solve(0, n)
leading stack overrun. there's no side effects or external variables affect solve
, make behave differently same arguments.
i don't understand solution, can't tell how fix it, intent queenstack
visible across calls, in case make sense make global, or pass solve
reference.
now why finishes fine when run outside of debugger. guess use kind of non-windows system (mac or linux) , run terminal. way program still crashes, not show in obvious way. way see if finished print $?
after executing program:
a@a-dev:~$ ./crash_me a@a-dev:~$ echo $? 1
if program executed normally, return code should zero.
Comments
Post a Comment