Eight Queens
1 Public classEightqueen {2 3 Private Static Final intROW = 4;4 Private Static Final intCOL = 4;5 6 Private Static intCount = 0;//Eight the number of the Queen's Solutions7 8 Private Static Boolean[] maps =New Boolean[ROW] [COL];//Initializes a two-dimensional array, simulates the 8*8 checkerboard, and the default value is false to indicate no queen9 Ten //How to put the Queen? One /** A * Place the Queen of the first row - * @paramrow starts with the Queen on line No. 0. - */ the Public Static voidPutqueen (introw) { - - //Export of recursion - if(row = = row) {//row=8, the 9th row, then the front 8 rows is ok + Printqueen (); - return; + } A at //Put the Queen in column J of row No. - for(intj = 0; J < COL; J + +) { - //If you can put it, put the Queen at that point. - if(IsOK (Row, J)) { -MAPS[ROW][J] =true; -Putqueen (row + 1);//after the line is put down and put down a line "recursion to put the Queen", the algorithm has jumped inMAPS[ROW][J] =false;//backtracking, when the row+1 line piece is not satisfied, will go back to the first row - } to } + } - the //if you want to place the Queen at the (x, y) point, you need to first determine whether the point can be placed * Public Static BooleanIsOK (intXinty) { $ Panax Notoginseng //Traverse a two-dimensional array to determine whether there are queens in 4 directions - for(inti = 0; i < ROW; i++) { the for(intj = 0; J < COL; J + +) { + //positive hypotenuse x-y fixed value, inverse bevel x+y as fixed value A if(i = = x | | j = = Y | | i-j = = XY | | i + j = = x +y) { the //judge whether there is a queen in 4 directions + if(Maps[i][j]) {//returns False if a queen is placed at that point - return false; $ } $ } - } - } the - return true;Wuyi } the - Public Static voidPrintqueen () { Wu -System.out.println ("++count" + "One Solution")); AboutSystem.out.println ("*******************"); $ for(inti = 0; i < ROW; i++) { - for(intj = 0; J < COL; J + +) { - if(Maps[i][j]) { -System.out.print ("Q"); A}Else { +System.out.print ("*"); the } - } $ System.out.println (); the } the } the the /** - * 4 Queen for the poor lifting method in */ the Private Static voidQueen () { the About for(inti = 0;i < 4;++i) the for(intj = 0;j < 4;++j) the for(intK = 0;k < 4;++k) the for(intm = 0; M < 4;++m) + if(!conflusion (i,j,k,m)) { -System.out.println ("[" +i+ "," +j+ "," + K + "," + M + "]"); the }Bayi the } the - Private Static BooleanConflusion (intIintJintKintm) { - the returnj = = I | | K = = I | | m = = I | | K = = J | | m = = J | | K = =m the|| Math.Abs (i-j) = = 1 | | Math.Abs (i-k) = = 2 the|| Math.Abs (i-m) = = 3 | | Math.Abs (j-k) = = 1 the|| Math.Abs (j-m) = = 2 | | Math.Abs (k-m) = = 1; - } the the Public Static voidMain (string[] args) { the 94System.out.println ("Backtracking method for 4 Queens"); thePutqueen (0);//let the Queen begin on line No. 0. theSystem.out.println ("Exhaustive method for solving 4 Queens"); the Queen ();98 } About}
Using Java to implement some common problems