您的位置:首页 > 其它

LeetCode 10.4 N-Qeens

2016-04-26 15:01 169 查看
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.."]
]

import java.util.Stack;
public class T1 { T1(int _n) { n = _n; f = new int[n]; } int n; int[] f; Stack<int[]> ans = new Stack<>();
public static void main(String[] args) { T1 t = new T1(8); t.DFS(0); t.print(); }
void DFS(int k) { if (k == n) { if (chack(n)) { int[] a = new int[n]; for (int i = 0; i < f.length; i++) { a[i] = f[i]; } ans.push(a); } } else { for (int i = 0; i < n; i++) { f[k] = i; if (chack(k)) DFS(k + 1); } } } boolean chack(int l) { for (int i = 0; i < l; i++) { for (int j = i + 1; j < l; j++) { if (Math.abs(f[j] - f[i]) == j - i || f[j] == f[i]) { return false; } } } return true; } void print() { int num = 1; while (!ans.isEmpty()) { System.out.println("============" + num + "======="); int[] arr = ans.pop();
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[i] != j) System.out.print('.'); else System.out.print('*'); } System.out.println(); } num++; } }}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: