N-Queens in Java using Stacks, Keeps taking the same route after backtracking -
title pretty says all. i've been working on , can't figure out way prevent happening. perhaps way store invalid placements? or how implement way 'resume' last time @ row doesn't pick same value again?
ignore while i, debugging. same prints.
import java.util.stack; public class nqueens { //***** fill in code here ***** //feel free add additional methods necessary //finds , prints out solutions n-queens problem public static int solve(int n) { //***** fill in code here ***** //scaffolding code stacks.pdf //------------------------------------------------------------------------------------------------------------------ // create empty stack , set current position 0 stack<integer> s = new stack<integer>(); int column = 0; int row = 0; int solutionscount = 0; int = 0; //repeat { //loop current position last position until valid position found //current row while (i < 5){ for(column = 0; column < n ;column++) { //if there valid position system.out.println("top of loop"); system.out.println("column/index = " + column + "; row is: " + row); system.out.println("stack size = " + s.size()); system.out.println(); if (isvalid(s, column, row)) { s.push(column); //push position stack, set current position 0 // move next ro row++; column = 0; }//if }//for //if there no valid position if(!isvalid(s, column, row) || column >= n){ //if stack empty, break // stop search if(s.size() == 0){ break; //stop search }//if //else pop stack, set current position next position // backtracking previous row else{ s.pop(); column++; row--; }//else }//if //if stack has size n { // solution found if (s.size() == n){ solutionscount++; printsolution(s); //pop stack, set current position next position // backtracking find next solution s.pop(); row--; column++; }//if else { }//else i++; // make sure change when not bug testing 4x4 }//end loop //update following statement return number of solutions found return solutionscount; }//solve()
this looks homework, here pointers:
- you modifying
column
variable afterfor
loop. obviously, intend value carry on next iteration ofwhile
. first thing whenwhile
starts again setcolumn
0
for (column = 0; ....)
, overrides value. informationcolumn
supposed carry 1 iteration ofwhile
next? - you setting
column
0
insidefor
loop incremented1
column++
before nextfor
iteration. - you using
column
inif
statement after loop. expect value of variable afterfor
loop completes? - after
for
loop have 2if
statements trying check same condition -- whetherfor
loop found solution. secondif
clearer it. need bothif
s? - you putting
column
values stack, when pop them off stack, discard them. don't have use these values?
Comments
Post a Comment