(Easy) Backtracking: N-Queen Problems- Algorithm
Description:
Solution:
class Main { public static void main(String[] args) { System.out.println("Hello world!"); int size = 8; char [][] map = new char[size][size]; for(int i =0; i<size; i++){ for(int j=0; j<size; j++){ map[i][j] = '-'; } } Main m = new Main(); if(m.Solve(map,0)){ printSolution(map); }; } static void printSolution(char board[][]) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) System.out.print(" " + board[i][j] + " "); System.out.println(); } } boolean Solve(char[][]map , int cnt){ if(cnt>=8){ return true; } for(int tmp = 0; tmp<8; tmp++){ if(Validate(map,cnt, tmp)){ map[cnt][tmp]='Q'; if(Solve(map,cnt+1)){ return true; }else{ map[cnt][tmp] ='-'; } } } return false; } public boolean Validate(char[][] map,int i, int j ){ //column check for(int m = 0; m< map.length; m++){ if(m!=i){ if(map[m][j]=='Q'){ return false; } } } // row check for(int k = 0; k<map[0].length;k++){ if(k!=j){ if(map[i][k]=='Q'){ return false; } } } // dia1 check //(k+l) == (i+j)) || ((k-l) == (i-j) for(int m=0; m<map.length; m++){ for(int k = 0; k<map[0].length; k++){ if((i+j)==(m+k) || (i-j)==(m-k)){ if(map[m][k]=='Q'){ return false; } } } } return true; } }