leetcode -- N-Queens
2013-08-11 14:18
267 查看
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
For example,
There exist two distinct solutions to the 4-queens puzzle:
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 static void main(String[] args) { ArrayList<String[]> result = solveNQueens(4); System.out.println(result.size()); for(int i = 0; i < result.size(); i++){ System.out.println("solution:" + i); for(int j = 0; j < result.get(i).length; j++){ System.out.println(result.get(i)[j]); } } } public static ArrayList<String[]> solveNQueens(int n) { // Start typing your Java solution below // DO NOT write main() function ArrayList<String[]> result = new ArrayList<String[]>(); int depth = 0; int[] rows = new int ; for (int i = 0; i < n; i++) { rows[i] = n + 1; } dfs(depth, rows, n, result); return result; } public static void dfs(int depth, int[] rows, int n, ArrayList<String[]> result) { if (depth == n) { String[] s = new String ; for (int i = 0; i < n; i++) { int m = rows[i]; StringBuilder tmp = new StringBuilder(); for (int j = 0; j < n; j++) { if (j == m) { tmp.append("Q"); continue; } tmp.append("."); } s[i] = tmp.toString(); } result.add(s); return; } for (int i = 0; i < n; i++) { rows[depth] = i; if (isValid(rows, depth)) { dfs(depth + 1, rows, n, result); } } } public static boolean isValid(int[] rows, int depth) { for (int i = 0; i < depth; i++) { if (rows[i] == rows[depth] || Math.abs(rows[i] - rows[depth]) == Math.abs(i - depth)) { return false; } } return true; } }
相关文章推荐
- [leetcode]N-Queens
- 【leetcode】N-Queens
- leetcode 72: N-Queens
- 【每天一道leetcode】1:N-Queens
- LeetCode 51 N-Queens
- Leetcode-N-Queens
- LeetCode N-Queens II
- leetcode 52. N-Queens II & leetcode 51 N-Queens (N皇后问题)
- leetcode 050 —— N-Queens
- leetcode N-Queens I & II N皇后问题
- 【LeetCode】51. N-Queens
- LeetCode: N-Queens [050]
- LeetCode 51 - N-Queens
- leetcode - N-Queens
- [leetcode] N-Queens
- LeetCode_51---N-Queens
- LeetCode : N-Queens
- [leetcode] 51. N-Queens
- Leetcode 51. N-Queens
- leetcode 72: N-Queens