First of all Happy New Years Eve everyone! I’m simply trying to solve 8 Queens Problem
with recursive way and find all the possible answers. However, when I try to run it, Eclipse is terminating my program without any output to console. I suspect that I have problem with my recusion logic but couldn’t figure out how or why.
Here is the Queens class with main in it:
package Queens; public class Queens { public static void main(String[]args) { int[][] map = new int[8][8]; int[] column = new int[8]; Problem p = new Problem(); //All possible Queen start positions send to start() method //Column array used for storing queens column position to check for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { map[i][j] = 1; column[j] = 1; p.start(map, column); map[i][j] = 0; column[j] = 0; } } } }
And Problem class, main source of work:
package Queens; public class Problem { public void start(int[][] mapCopy, int[] columnCopy) { int[][] map = new int[8][8]; int[] column = new int[8]; boolean end = true; //Copying the arrays for avoiding 'pass-by-value' System.arraycopy(mapCopy, 0, map, 0, 8); System.arraycopy(columnCopy, 0, column, 0, 8); //Check for all queens placed for(int i = 0; i < 8; i++) { if(column[i] == 0) end=false; } //Printing answers that placed all queens right place if(end == true) { for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { System.out.print(map[i][j] + " "); } System.out.println(); } System.out.println(); } //Recursive Logic: I tried to send every possibilty to next call //Using column[] array for(int i = 0; i < 8; i++) { for(int j = 0; j < 8; j++) { if(column[j] != 1) { map[i][j] = 1; //if a queen has right place start() method calls for next step //And resets remaining stuation //Before for loop continues for other possibilities if(check(map, i, j)) { column[j] = 1; start(map, column); column[j] = 0; System.out.println("lol"); } else { map[i][j] = 0; } } } } } //Simple dimensional checks public boolean check(int[][] mapCopy, int i, int j) { int[][] map = new int[8][8]; int k = 0; int l = 0; System.arraycopy(mapCopy, 0, map, 0, 8); for(k = 0; k < 8; k++) { if(map[k][j] == 1) return false; } for(l = 0; l < 8; l++) { if(map[i][l] == 1) return false; } k = i; l = j; for(k = i; k < 8; k++) { if(map[k][l] == 1) return false; l++; } k = i; l = j; for(k = i; 0 <= k; k--) { if(map[k][l] == 1) return false; l++; } k = i; l = j; for(k = i; k < 8; k++) { if(map[k][l] == 1) return false; l--; } k = i; l = j; for(k = i; k < 8; k--) { if(map[k][l] == 1) return false; l--; } return true; } }