Relatively simple, nonsense not to say, on the code:
Public classNqueen {//For example: Position[1]=3, which indicates that the third column of the first row has a queen Private int[] position; //total number of methods Private intTotal ; Private intNumofqueens; PublicNqueen (intNthrowsException {if(n<0) Throw NewException ("Can not be negative ..."); Else { //Position[0] Noposition=New int[N+1]; Numofqueens=N; Total= 0; } } Public intNqueen () {Putqueen (1); returnTotal ; } //put a queen in the first row. Private voidPutqueen (introw) { if(row==numofqueens+1) { Total++; return; } //traverse the first row line to place the Queen's All possibilities for(inti=1;i<=numofqueens;i++) {Position[row]=i; //If you put it in a reasonable if(Checkifvalid (Row)) Putqueen (Row+1);//then the recursive solution } } //Check if the place is reasonable. Private BooleanCheckifvalid (introw) { if(row==1) return true; for(inti=1;i<row;i++) { if(!Check (i,row))return false; } return true; } Private BooleanCheckintAintb) {if(Position[a]==position[b] | |(A-b) = = (Position[a]-position[b]) | |(A-b) ==-1* (position[a]-Position[b])) return false; return true; } /** * @paramargs *@throwsException*/ Public Static voidMain (string[] args)throwsException {nqueen NQ=NewNqueen (8); System.out.println (Nq.nqueen ()); //TODO auto-generated Method Stub }}
N Queen problem--recursive solution