Java for LeetCode 051 N-Queens

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.

解题思路:经典的八皇后问题,由于之前在《JAVA语言程序设计》中exerice6-22中做过这种问题,代码直接拿来修改下即可,JAVA实现如下:

static public List<String[]> solveNQueens(int n) {
	 List<String[]> list=new ArrayList<String[]>();
	 if(n==1){
		 String[] str={"Q"};
		 list.add(str);
		 return list;
	 }
//	 int count = 0;
	    int[] queens = new int[n]; // queens are 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] == column)
        return false;
    for (int row = k - 1, column = j + 1; row >= 0 && column <= n-1; row--, column++)
      if (queens[row] == column)
        return false;
    return true;
  }
时间: 2024-08-15 01:55:16

Java for LeetCode 051 N-Queens的相关文章

Java for LeetCode 216 Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Ensure that numbers within the set are sorted in ascending order. Example 1

Java for LeetCode 128 Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your algorithm should run i

Java for LeetCode 098 Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

Java for LeetCode 057 Insert Interval

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge

Java for LeetCode 059 Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]] 解题思路: 参考Java for LeetCode 054 Spiral Matrix,修改下

Java for LeetCode 107 Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / 15 7 return its bottom-up level order trave

Java for LeetCode 108 Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 解题思路: 首先要理解,什么叫做height balanced BST Java for LeetCode 110 Balanced Binary Tree,然后就十分容易了,JAVA实现如下: public TreeNode sortedArrayToBST(int[] nums) { return

Java for LeetCode 090 Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If nums = [1,2,2], a soluti

Java for LeetCode 214 Shortest Palindrome

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", return "aaacecaaa&qu