The classic 8 queen, Recursive Backtracking is solvable. At the same time, I also learned a convenient setCharAt () method in StringBuilder.
Package Level4; import java. util. arrayList; import java. util. arrays;/***** N-Queens ** The n-queens puzzle is the problem of placing n queens on an n × n chessboard such that no two queens attack each other. http://www.leetcode.com/wp-content/uploads/2012/03/8-queens.png Given an integer n, return all distinct solutions to the n-queens puzzle. each solution contains a distinct board configuration of the n-queens 'placement, where 'Q' and '. 'Both indicate a queen and an empty space respectively. for example, There exist two distinct solutions to the 4-queens puzzle :[[". Q .. ", // Solution 1 "... Q "," Q... ",".. q. "], ["... q. ", // Solution 2" Q... ","... Q ",". Q .. "] **/public class S51 {public static void main (String [] args) {System. out. println (solveNQueens (4);} public static ArrayList <String []> solveNQueens (int n) {ArrayList <String []> ret = new ArrayList <String []> (); int [] queenList = new int [n]; placeQueen (queenList, 0, n, ret); return ret;} // Recursive Backtracking of the 8 queens. The key record is the public static void placeQueen (int [] queenList, int row, int n, arrayList <String []> ret) {// Base Case. if (row = n) {StringBuilder [] sol = new StringBuilder [n] has been completed. // each object in the logarithm group must have a new for (int I = 0; I <n; I ++) {sol [I] = new StringBuilder (); for (int j = 0; j <n; j ++) {sol [I]. append (". ") ;}} // place queen for (int I = 0; I <n; I ++) {sol [I] in the corresponding place. setCharAt (queenList [I], 'q');} String [] ss = new String [n]; for (int I = 0; I <n; I ++) {ss [I] = sol [I]. toString ();} ret. add (ss); return;} // start the search for this row // traverse all columns in the row to test which position is safe for (int col = 0; col <n; col ++) {if (isSafe (queenList, row, col) {queenList [row] = col; placeQueen (queenList, row + 1, n, ret) ;}}// determine whether the coordinates (row, col) are safe (check rows, columns, and diagonal lines) // store rows in the queenList, column coordinate pair, that is, queenList [row] = col public static boolean isSafe (int [] queenList, int row, int col) {for (int preRow = 0; preRow <row; preRow ++) {int preCol = queenList [preRow]; if (preRow = row) {// theoretically no check is required, because preRow is always less than the return false of row ;} if (preCol = col) {// check whether return false is in the same column;} if (row-preRow = col-preCol) {// return false on the diagonal line ;} if (preRow + preCol = row + col) {// return false on the diagonal line;} return true ;}}