/**
* Function: Print the eight queens on the 8*8 Board of the various pendulum, where each queen does not walk, different columns, also not on the diagonal.
The "diagonal" here refers to all the diagonal lines, not just the two diagonals that divide the entire chessboard.
*/
static int grid_size=8;/** * Idea: Only one queen can be placed on each line, so you do not need to store the chessboard as a complete 8*8 matrix, only one-dimensional array, where columns[r]=c means that there is a queen in row C of R. * @param row * @param columns * @param results */public static void Placequeen (int row,integer[] Columns,arraylist<inte Ger[]> results) {if (row==grid_size) {/*creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. * The general intent are that, for any object x, the Expression:x.clone ()! = Xwill be true. * And that the Expression:x.clone (). GetClass () = = X.getclass () would be true. *but these is not absolute requirements. While it was typically the case that:x.clone (). Equals (x) would be true, and this is a absolute requirement. */results.add (Columns.clone ());} else{for (int col=0;col<grid_size;col++) {if (Checkvalid (Columns,row,col)) {columns[row]=col;//placed Queen Placequeen ( row+1, columns, results);}}} /** * Check (row,column) whether the Queen can be placed, method: * Check if there is no other queen in the same column or diagonal, do not have to check whether on the same line, because when calling Placequeen, only one queen will be placed at a time. So, this line is empty. * @param columns * @param Row * @param column * @return */public static Boolean checkvalid (integer[] columns,int row,int column) {for (int r=0;r<r ow;r++) {int c=columns[r];/* checks if the same column has Queen */if (C==column) return false;/* Check the diagonal: * If the distance between the two lines equals the distance of two columns, then two queens are on the same diagonal. */int Columndistance=math.abs (c-column); int rowdistance=row-r;//row>r, without absolute value if (columndistance==rowdistance) return false;} return true;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
9.9 Recursive and dynamic Planning (ix)--n Queen