Java for Leetcode 051 N-queens

Source: Internet
Author: User

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 Indi Cate a queen and an empty space respectively.

Problem-solving ideas: The classic eight Queen question, because before in the Java language programming exerice6-22 in this problem, the code directly to modify the next, Java implementation is as follows:

static public list<string[]> solvenqueens (int n) {list<string[]> list=new arraylist<string[]> (); N==1) {string[] str={"Q"}; list.add (str); return list;}     int count = 0; int[] Queens = new Int[n];     Queens is placed at (I, queens[i]) for (int i = 0; i < n; i++) queens[i] = 1;     Queens[0] = 0;    int k = 1;      while (k >=0) {int J = findposition (k, queens,n);        if (j ==-1) {Queens[k] =-1; k--;        Back track to the previous row} else {queens[k] = j;           if (k = = n-1) {//count++;          String[] Queenarray=new String[n];          for (int i=0;i<n;i++) {StringBuilder sb=new StringBuilder ();          for (int j2=0;j2<n;j2++) {if (J2==queens[i]) sb.append (' Q ');          else Sb.append ('. ');          } queenarray[i]=new String (SB);        } list.add (Queenarray);        } else {k++;   }}} return list; } public static int findposition (int k, int[] queens,int n) {int start = queens[k] = = 1? 0:queens[k] + 1;     for (int j = start; J < N; j + +) {if (IsValid (K, J, Queens,n)) return J;  } return-1; } public static Boolean isValid (int k, Int J, int. Queens[],int N) {for (int i = 0; i < K; i++) if (Queens[i]    = = j) return false; for (int row = k-1, column = j-1; row >= 0 && column >= 0; row--, column--) if (queens[row] = = Colu    MN) return false; for (int row = k-1, column = j + 1; row >= 0 && column <= n-1; row--, column++) if (queens[row] = = Co    Lumn) return false;  return true; }

Java for Leetcode 051 N-queens

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.