3.6. N queens
在一个 n 大小的象棋盘中放置 n 个皇后,没有两个皇后可以相互攻击。最常见的 n queens puzzle 是 8 个queuzzle,有 n = 8 :
约束:
- 使用主板的 n 列和 n 行。
- 在主板上放置 n queens。
- 无法相互攻击两个频率。queen 可攻击同一横向、垂直或部门其他任何频率的其他频率。
本文档主要使用四个不同点。
建议的解决方案可能是:
图 3.1. 错误解决方案,用于 4 queens puzzle
以上解决方案是错误的,因为 queens A1
和 B0
可以相互攻击(因此可以说 B0
和 D0
)。删除 queen B0
会尊重"不两种 queens"约束,但会破坏 "place n queens" 约束。
以下是一个正确的解决方案:
图 3.2. Four quele queuzzle 的正确解决方案
所有约束都已满足,因此解决方案正确。
请注意,大多数 n 个词汇都有多个正确的解决方案。我们将专注于查找特定 n 的正确解决方案,而不是查找特定 n 可能的正确解决方案数量。
问题大小
4queens has 4 queens with a search space of 256. 8queens has 8 queens with a search space of 10^7. 16queens has 16 queens with a search space of 10^19. 32queens has 32 queens with a search space of 10^48. 64queens has 64 queens with a search space of 10^115. 256queens has 256 queens with a search space of 10^616.
N queens 示例的实现还没有优化,因为它作为新手示例的功能。然而,它可以轻松地处理 64 queens。出现了一些变化,它已被显示,可轻松处理 5000 queens 等等。
3.6.1. N queens 的域模型
这个示例使用域模型解决四条问题。
创建域模型
好的域模型可以方便理解和解决您的规划问题。
这是 n queens 示例的域模型:
public class Column { private int index; // ... getters and setters }
public class Row { private int index; // ... getters and setters }
public class Queen { private Column column; private Row row; public int getAscendingDiagonalIndex() {...} public int getDescendingDiagonalIndex() {...} // ... getters and setters }
计算搜索空间.
Queen
实例有一个Column
(例如:0 为列 A,1 为列 B, …)和一个Row
(its 行,例如 0 代表行 0,1 是行 1, …)。可以根据列和行计算升序行和降序行。
列和行索引从主板的左上角开始。
public class NQueens { private int n; private List<Column> columnList; private List<Row> rowList; private List<Queen> queenList; private SimpleScore score; // ... getters and setters }
查找解决方案
单个
NQueens
实例包含所有Queen
实例的列表。它是Solution
实施,它将提供给、被解决并从 Solver 中检索。
请注意,在四个 queens 示例中,NQueens getN ()
方法始终返回四个。
图 3.3. Four Queens 的解决方案
columnIndex | rowIndex | ascendingDiagonalIndex (columnIndex + rowIndex) | descendingDiagonalIndex (columnIndex - rowIndex) | |
---|---|---|---|---|
A1 | 0 | 1 | 1 (**) | -1 |
B0 | 1 | 0 (*) | 1 (**) | 1 |
C2 | 2 | 2 | 4 | 0 |
D0 | 3 | 0 (*) | 3 | 3 |
当两个 queens 共享同一列时,行或横线,如(*)和(**),它们可以相互攻击。