題目:在8x8對國際象棋上擺放8個皇后,使其不能相互攻擊,即任意兩個皇后不得處在同一行、同一列、同一對角線上。如圖是一種結(jié)果:

image.png
請問有多少種符合條件的擺法?
解法:就是全排列,只是對排列結(jié)果進行判斷,是否滿足給定條件。
可以定義一個數(shù)組columnIndex[8],下標代表所處的行數(shù),值代表所處的列數(shù),如columnIndex[0]=2表示,第0行第2列。對數(shù)組進行全排列,排列后的數(shù)組如果任意兩行i、j都滿足i-j==columnIndex[i] - columnIndex[j] 或 j-i == columnIndex[i]-columnIndex[j],則將數(shù)組加入結(jié)果集中。
private List<List<Integer>> internationalQueue() {
int[] columnIndex = new int[]{0, 1, 2, 3, 4, 5, 6, 7};
List<List<Integer>> result = new ArrayList<>();
queuePermutation(result, columnIndex, 0);
return result;
}
private void queuePermutation(List<List<Integer>> result, int[] nums, int index) {
if (index >= nums.length) {
for (int i = 0; i < nums.length; ++i) {
for (int j = i+1; j < nums.length; ++j) {
if (j - i == Math.abs(nums[j] - nums[i])) {
return;
}
}
}
List<Integer> numbers = new ArrayList<>();
for (int num : nums) {
numbers.add(num);
}
result.add(numbers);
} else {
for (int i = index; i < nums.length; ++i) {
if (i == index || nums[i] != nums[index]) {
int temp = nums[i];
nums[i] = nums[index];
nums[index] = temp;
queuePermutation(result, nums, index + 1);
temp = nums[i];
nums[i] = nums[index];
nums[index] = temp;
}
}
}
}