1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| * @Description: 打印所有"8皇后"的可能位置 * @param * @return void */ public static void eightQueen() { int[] queens = { 0, 1, 2, 3, 4, 5, 6, 7}; getAllArrange(queens, 0, queens.length - 1); }
* @Description: 数组全排列筛选 * @param @param nums * @return void */ private static void getAllArrange(int[] nums, int start, int end) { if (start > end) { System.out.println(Arrays.toString(nums)); return; } boolean isContinue = false; for (int i = start; i <= end; isContinue=false,i++) { exch(nums, start, i); for (int a = start - 1; a >= 0; a--) { if (isDiagonal(nums, a, start)) { exch(nums, start, i); isContinue=true; break; } } if(isContinue) { continue; } getAllArrange(nums, start + 1, end); exch(nums, start, i); } }
* * @Description: 判断两个位置是否在同一对角线上 * @param @param nums * @param @param i * @param @param j * @param @return * @return boolean */ private static boolean isDiagonal(int[] nums, int i, int j) { int result = nums[i] - nums[j]; return (i - j) == result || (j - i) == result; }
* * @Description: 交换数组中的两个数的值 * @param @param nums * @param @param i * @param @param j * @return void */ private static void exch(int[] nums, int i, int j) { if (i == j) return; nums[i] ^= nums[j]; nums[j] ^= nums[i]; nums[i] ^= nums[j]; }
|