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