Here, the backtracking algorithm is going to be a good look.
To test if a location is valid, if it is valid, to test the next location (DFS), fallback if invalid
1. Define a solution space and store a solution space
2.DFS (considered DFS for the moment)
Here n Queens is implemented by recursion + backtracking
1 Packagecom.gxf.backtracking;2 3 /**4 * N Queens question5 * @authorAdministrator6 *7 */8 Public classQueen {9 intNum_queen;//Number of QueensTen intSolution[];//Solution[i] = k denotes the first row of the Queen in column K, solution for the solution space One intsum = 0; A - PublicQueen (intnum) { -Num_queen =num; theSolution =New int[Num_queen + 1]; - } - - /** + * The location of the K-Queens is valid - * The columns of the K-Queens are kept in solution[k], compared with the k-1 of the former queen + * @paramk A * @return at */ - BooleanIsValid (intk) { - for(inti = 1; I < K; i++){ - if(Solution[i] = = Solution[k] | | Math.Abs (k-i) = = Math.Abs (Solution[k]-Solution[i])) - return false; - } in return true; - } to + /** - * Start putting the nth queen the * @paramQueen * */ $ Public voidPlacequeen (intN) {Panax Notoginseng if(N >Num_queen) - { the showsolution (); + System.out.println (); Asum++; the } + Else - for(inti = 1; I <= Num_queen; i++){ $Solution[n] = i;//n Queens put in column I $ if(IsValid (n)) -Placequeen (n + 1); - } the } - Wuyi /** the * Print out the results - */ Wu Public voidshowsolution () { - for(inti = 1; I <= Num_queen; i++){ About for(intj = 1; J <= Num_queen; J + +){ $ if(J = =Solution[i]) -System.out.print (' Q ' + "")); -System.out.print (0 + ""); - } A System.out.println (); + } the } - $ Public Static voidMain (string[] args) { theQueen Queen =NewQueen (4); the theQueen.placequeen (1); theSystem.out.println ("sum =" +queen.sum); - } in the}
The n queen problem of backtracking (SU) algorithm