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
columnvariable afterforloop. obviously, intend value carry on next iteration ofwhile. first thing whenwhilestarts again setcolumn0for (column = 0; ....), overrides value. informationcolumnsupposed carry 1 iteration ofwhilenext? - you setting
column0insideforloop incremented1column++before nextforiteration. - you using
columninifstatement after loop. expect value of variable afterforloop completes? - after
forloop have 2ifstatements trying check same condition -- whetherforloop found solution. secondifclearer it. need bothifs? - you putting
columnvalues stack, when pop them off stack, discard them. don't have use these values?
Comments
Post a Comment