题目:在8x8对国际象棋上摆放8个皇后,使其不能相互攻击,即任意两个皇后不得处在同一行、同一列、同一对角线上。如图是一种结果:

请问有多少种符合条件的摆法?
解法:就是全排列,只是对排列结果进行判断,是否满足给定条件。
可以定义一个数组columnIndex[8],下标代表所处的行数,值代表所处的列数,如columnIndex[0]=2表示,第0行第2列。对数组进行全排列,排列后的数组如果任意两行i、j都满足i-j==columnIndex[i] - columnIndex[j]
或 j-i == columnIndex[i]-columnIndex[j]
,则将数组加入结果集中。
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;
}
}
}
}
网友评论