LeetCode :My solution N-Queens

N-Queens

Total Accepted: 15603 Total
Submissions: 60198My Submissions

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two 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 two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
public class Solution {
  public List<String[]> solveNQueens(int n) {
        List<String[]> result = new ArrayList<String[]>();
        if ( n < 1) {
            return result ;
        }
        List<List<Integer>> storeArray = new ArrayList<List<Integer>>();
        helper(n, new ArrayList<Integer>(), storeArray);
		result = drawPicture(storeArray,n);
        return result;
    }

    private List<String[]> drawPicture(List<List<Integer>> storeArray ,int n) {
    	List<String[]> drawedPicture = new ArrayList<String[]> ();
    	for (int i = 0; i < storeArray.size();i++) {
    		String[] str = new String[n];
    		for (int j = 0; j < n; j++) {
    		    str[j] = new String("");
    			for (int w = 0; w < n; w++) {
    				if (storeArray.get(i).get(j) == w) {
    					str[j] +="Q";
    				} else {
    					str[j] +=".";
    				}
    			}

    		}
    		drawedPicture.add(str);
    	}
    	return drawedPicture;
	}

	boolean isValid(ArrayList<Integer> cols, int col) {
    	   int newX = col;
    	   int newY = cols.size();
    	for (int y = 0; y < cols.size(); y++) {
    		int x = cols.get(y);

    		if (newX == x) {
    			return false;
    		}
    		if (newX - newY == x - y) {
    			return false;
    		}
    		if (newX + newY == x + y){
    			return false;
    		}
    	}
    	return true;
    }
    public void helper(int n, ArrayList<Integer> cols,  List<List<Integer>> storeArray) {
    	if (cols.size() == n) {
    		storeArray.add(new ArrayList<Integer>(cols));
    		return;
    	}
    	for (int i = 0; i < n; i++) {
    		if (!isValid(cols, i)) {
    			continue;
    		}
    		cols.add(i);
    		helper(n, cols, storeArray);
    		cols.remove(cols.size() - 1);
    	}
    }
}

时间: 2024-10-22 05:05:53

LeetCode :My solution N-Queens的相关文章

LeetCode My Solution: Minimum Depth of Binary Tree

Minimum Depth of Binary Tree Total Accepted: 24760 Total Submissions: 83665My Submissions Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

Triangle LeetCode |My solution

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i

【leetcode】solution in java——Easy2

转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6410409.html 6:Reverse String Write a function that takes a string as input and returns the string reversed. 此题:字符串反转题. 思路:此题大一学C++的时候上机题就做过了,当时思路是:把String转化为char[],从尾到头遍历一次倒序地把字符复制到另一个数组(从头到尾),然后把新数组toStrin

Leetcode solution 173: Binary Search Tree Iterator

Problem Statement Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Example: BSTIterator iterator = new BSTIterator(ro

Leetcode solution 124: Binary Tree Maximum Path Sum

Problem Statement Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at leas

Baozi Leetcode solution 201: Bitwise AND of Numbers Range

Problem Statement Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. Example 1: Input: [5,7] Output: 4 Example 2: Input: [0,1] Output: 0 Problem link Video Tutorial You can find t

Baozi Leetcode solution 135: Candy

Problem Statement There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating

Leetcode solution 322: Coin Change

Problem Statement  You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combin

Baozi Leetcode solution 54: Sprial Matrix

Problem Statement  Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Example 1: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: [ [1, 2, 3, 4], [5,