java - Optimizing N Queens code to avoid stack overflow -
I try to write a Java class to solve the problem of n queens using stacking and recursion of some squares I am stuck in the answer grid (two dimensional arrays), but I have struck a dead wall which has a heavy overflow for recursion at n = 8 (the maximum recursion has reached 2298) so I I am thinking that there is no way to bypass this deceased. Make some complex (or tell me a tutorial / example), such as allotting more heaps of space (if possible?) Or using multi threads ... or please advise on optimizing the code. Thanks in advance
Public Zero Rider () {this.gridPile.push (copyGrid (grid)); {Int row = gridPile.size () - 1; If (gridPile.size () == 0) line = 0; Choose grid spaces (this grid, find available availability (grid, line)); If (gridPile.size () == this.taille) {gridSolutions.push (copyGrid (grid)); Grid = grid.php (); Boolean wrong = true; While (wrong) {try {MakeNextUnavailable (grid, gridpile size ()); Wrong = wrong; } Hold (absence exception R1) {try {grid = grid.pile.pop ()}} hold (java.util.EmptyStackException r2) {return; }}}}} Hold (InvalidPositionException e1) {this.grid = gridPile.pop (); Boolean error = true; While {error} {try {MakeNextUnavailable (grid, gridpile. Size ()); Error = false; } Hold (absence eclipse er) {try {this.grid = grid.pile.pop (); } Hold (java.util.EmptyStackException err) {return; }}}} Hold (java.lang.ArrayIndexOutOfBoundsException e2) {return; } This.resoudre (); } Select Private Static Zero GridSpace (int [] [] Grid, Position A) {Grid [a.getLigne ()] [a.getColonne ()] = 1; FillNotAvailable (grid, A); }
direct answer: to completely push There is no need to grid on the stack, and you may want to represent the grid in the form of an array of 8 integers, while pointing the position of the queen in each row.
Genuine problem: Your code is too long and too confused. keep it simple! The queen's problem is usually & lt; Each of the 10 lines is resolved with two functions: it is simple:
Add some output code and a main program, and you are finished! public static bullion resolution (final entry board) {for (int i = 0; i & lt; board length; i ++) {for (int j = i + 1; j and lt; board; langue; j ++) {if (board [i] == board [j] ) Returned incorrectly; // same column "|" If (board [i] -b [j] == i-j) incorrect return; // Diagonal "\" if (board [i] -b [j] == j-i) false return; // diagonal "/"}} right back; } Public static zero solution (int depth, int [] board) {if (depth == board.line and isolution (board)) {outputSolution (board); } If (depth
Public stable zero outputsolation (final entry board) {System.out.println ("--- solution ---"); For (int i = 0; i
Comments
Post a Comment