您的位置:首页 > 产品设计 > UI/UE

N-Queens | & N-Queens II

2016-07-06 07:06 399 查看
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.

Example

There exist two distinct solutions to the 4-queens puzzle:

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


class Solution {

ArrayList<ArrayList<String>> solveNQueens(int n) {

ArrayList<ArrayList<String>> allList = new ArrayList<ArrayList<String>>();
if (n <= 0)
return allList;
Integer[] row = new Integer
;

ArrayList<ArrayList<Integer>> integerList = new ArrayList<ArrayList<Integer>>();

queen(0, n, row, integerList);

char[] arr = new char
;
Arrays.fill(arr, '.');

for (ArrayList<Integer> l : integerList) {
ArrayList<String> temp = new ArrayList<String>();
for (int i = 0; i < l.size(); i++) {
arr[l.get(i)] = 'Q';
temp.add(new String(arr));
arr[l.get(i)] = '.';
}
allList.add(new ArrayList<String>(temp));
}
return allList;

}

public void queen(int n, int count, Integer[] row, ArrayList<ArrayList<Integer>> list) {
if (n == count) {
list.add(new ArrayList<Integer>(Arrays.asList(row)));
return;
}

for (int i = 0; i < count; i++) {
row
= i;
if (isSatisfied(n, row)) {
queen(n + 1, count, row, list);
}
}
}

public boolean isSatisfied(int n, Integer[] row) {
for (int i = 0; i < n; i++) {
if (row[i] == row
)
return false;
if (Math.abs(row
- row[i]) == n - i)
return false;
}
return true;
}
};


N-Queens II

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

Example

For n=4, there are 2 distinct solutions.

class Solution {
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
public int totalNQueens(int n) {
//write your code here
int[] row = new int
;
int[] current = new int[1];
queen(0, n, row, current);
return current[0];
}

public void queen(int n, int count, int[] row, int[] current) {
if (n == count) {
current[0]++;
return;
}
for (int i = 0; i < count; i++) {
row
= i;
if (isSatisfied(n, row)) {
queen(n + 1, count, row, current);
}
}
}

public boolean isSatisfied(int n, int[] row) {
for (int i = 0; i < n; i++) {
if (row[i] == row
)
return false;
if (Math.abs(row
- row[i]) == n - i)
return false;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: