[Leetcode 51&52] N-queens I & II (n Queen's question)

Source: Internet
Author: User

Title Link: N-queens



Import Java.util.arraylist;import java.util.arrays;import java.util.list;/** * The N-queens puzzle is the problem of Placi ng N Queens on a nxn chessboard such that no, and Queens attack each other. 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, distinct solutions to the 4-queens puzzle:[[". Q.. ",//solution 1" ... Q "," Q ... ",".. Q. "], ["]. Q. ",//Solution 2" Q ... "," ... Q ",". Q.. "] * */public class Nqueens {//9/9 test Cases passed.//status:accepted//runtime:217 ms//submitted:0 minutes ago//backtracking//Time  Complexity O (n!) space complexity O (n) public int[] columns;//store placed Queens occupy columns, 0 not occupied, 1 occupied public int[] main_diag;//store placed Queens occupy the main diagonal, 0 is not occupied, 1 is occupied by public Int[] anti_diag;//Store placed Queens occupy the diagonal, 0 not occupied, 1 occupied public string[] st_str;public list<string[]> nqueens = new Arraylist&lt ; String[]> ();p ublic void Init (inT n) {columns = new int[n];        Main_diag = new int[2 * n];        Anti_diag = new int[2 * n];        Arrays.fill (columns, 0);        Arrays.fill (main_diag, 0);    Arrays.fill (anti_diag, 0); Createstring (n);} public void createstring (int n) {st_str = new string[n]; StringBuilder sb = new StringBuilder (); for (int i = 0; i < n; i++) {Sb.append (".");}    for (int i = 0; i < n; i++) {Sb.replace (i, i + 1, "Q"); St_str[i] = sb.tostring (); Sb.replace (i, i + 1, ".");}}        Public list<string[]> solvenqueens (int n) {//Initialize each state variable init (n);    int[] C = new Int[n];        Arrays.fill (C, 0);    DFS (C, 0);    return nqueens;    } public void Dfs (int[] C, int row) {int N = c.length;    means to find a viable solution if (row = = N) {string[] Nqueen = new String[n];    for (int i = 0; i < N; i++) {nqueen[i] = St_str[c[i]];}    Nqueens.add (Nqueen);    Return } for (int i = 0; i < N; i++) {//If not legal, this skips the current loop if (! ( Columns[i] = = 0&& Main_diag[i + row] = = 0&& Anti_diag[n-i + row] = = 0)) continue; Execute C[row] = i;columns[i] = 1;main_diag[i + row] = 1;anti_diag[n-i + row] = 1;dfs (C, row + 1);//undo C[row] = 0;columns[i]       = 0;main_diag[i + Row] = 0;anti_diag[n-i + row] = 0;} } public static void Main (string[] args) {Nqueens queens = new Nqueens (); list<string[]> result = Queens.solvenqueens (8); System.out.println (Result.size ());//for (int i = 0; i < result.size (); i++) {//for (int j = 0; J < Result.get (i). Len Gth J + +) {//system.out.println (Result.get (i) [j]);//}//system.out.println ();/}}}




Title Link: n-queens-ii


Import java.util.arrays;/** * Follow up for n-queens problem. Now, instead outputting board configurations and return the total number of distinct solutions. * */public class Nqueensii {//9/9 test Cases passed.//status:accepted//runtime:231 ms//submitted:0 minutes ago//backtracking// Time complexity O (n!) space complexity O (n) public int[] columns;//store placed Queens occupy columns, 0 not occupied, 1 occupied public int[] main_diag;//store placed Queens occupy the main diagonal, 0 is not accounted for, 1 is accounted for publ        IC int[] anti_diag;//store placed Queens occupy the diagonal, 0 not accounted for, 1 occupied public int total;public void init (int n) {columns = new int[n];        Main_diag = new int[2 * n];        Anti_diag = new int[2 * n];        Arrays.fill (columns, 0);        Arrays.fill (main_diag, 0);           Arrays.fill (anti_diag, 0);        Total = 0;//count} public int totalnqueens (int n) {//Initialize each state variable init (n);    int[] C = new Int[n];        Arrays.fill (C, 0);    DFS (C, 0);    return total;    } public void Dfs (int[] C, int row) {int N = c.length;    means to find a viable solution if (row = = N) {total + +;    Return } foR (int i = 0; i < N; i++) {//If not legal, this skips the current loop if (! (    Columns[i] = = 0&& Main_diag[i + row] = = 0&& Anti_diag[n-i + row] = = 0)) continue; Execute C[row] = i;columns[i] = 1;main_diag[i + row] = 1;anti_diag[n-i + row] = 1;dfs (C, row + 1);//undo C[row] = 0;columns[i]       = 0;main_diag[i + Row] = 0;anti_diag[n-i + row] = 0;} public static void Main (string[] args) {nqueensii queens = new Nqueensii (), for (int i = 0; i <; i++) {Syste M.OUT.PRINTLN (i + "-Queen has" + queens.totalnqueens (i) + "solution");}}} The Queen of output//0-has 1 solutions//1-Queen has 1 solutions//2-Queen has 0 solutions//3-Queen has 0 solutions//4-Queen has 2 solutions//5-Queen has 10 solutions//6-Queen has 4 solutions//7-Queen has 40 kinds of solution 8-Queens have 92 solutions//9-Queen has 352 solutions//10-Queen has 724 solutions//11-Queen has 2680 methods//12-Queen has 14200 solutions//13-Queen has 73712 solutions//14-Queen 365596 kinds Solution//15-Queen has 2279184 kinds of solution



[Leetcode 51&52] N-queens I & II (n Queen's question)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.