[Leetcode] N-Queens (Java)
2014-01-08 17:00
417 查看
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
indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
N皇后问题,DFS
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.."] ]
N皇后问题,DFS
public class Solution { public ArrayList<String[]> solveNQueens(int n) { ArrayList<String[]> res = new ArrayList<String[]>(); char[][] chars = new char ; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ chars[i][j]='.'; } } dfs(chars, res, 0, n); return res; } private void dfs(char[][] chars,ArrayList<String[]> res,int index,int n){ if(index==n){ String[] strs = new String ; for(int i=0;i<chars.length;i++) { strs[i]=new String(chars[i]); } res.add(strs); return; } for(int i=0;i<chars[index].length;i++){ if(check(chars,index,i)){ chars[index][i]='Q'; dfs(chars, res, index+1, n); chars[index][i]='.'; } } } private boolean check(char[][] chars, int index, int pivot) { for(int i=0;i<index;i++){ if(chars[i][pivot]=='Q') return false; } for(int i=index-1, j=pivot-1;i>=0&&j>=0;i--,j--){ if(chars[i][j]=='Q') return false; } for(int i=index-1, j=pivot+1;i>=0&&j<chars[i].length;i--,j++){ if(chars[i][j]=='Q') return false; } return true; } }
相关文章推荐
- N-Queens leetcode java
- LeetCode-51. N-Queens (JAVA)(打印N皇后解集)
- leetcode:N-Queens 【Java】
- (java)leetcode-51:N-Queens
- N-Queens leetcode java
- N-Queens II leetcode java
- (Java)LeetCode-51. N-Queens
- [LeetCode][Java] N-Queens
- [leetcode-51]N-Queens(java)
- Java for LeetCode 051 N-Queens
- leetcode Regular Expression Matching(Java)
- Java [leetcode 24]Swap Nodes in Pairs
- LeetCode[263] Ugly Number(Java)
- [LeetCode][Java] Minimum Depth of Binary Tree
- [LeetCode-Java]36. Valid Sudoku
- [LeetCode][Java] Longest Substring Without Repeating Characters
- [LeetCode][Java] 3Sum Closest
- [Leetcode] n queens n皇后问题
- Unique Binary Search Trees II leetcode java
- Java for LeetCode 062 Unique Paths