问题描述
我正在研究一个解决数独的项目。这是我的大学课程的一部分,当我一直在计划方法时,我想尝试使用优先级队列来确定接下来要在数独中处理的单元。
我应该在优先级队列中存储什么?
我本以为可以存储单元格(例如grid [x] [y]),但这是棘手的部分。我根据可以进入该单元格的可能组合的数量,为某个位置的单元格确定了优先级。但是我无法存储每个单元格有多少组合,因此我考虑使用地图数据类型将网格位置存储为键,将可能的组合存储为值。然后我将使用这些值的优先级队列,这些值会将我指向网格位置。
我对Java或数据结构的经验不足,但是我真的很喜欢这种方法。任何帮助将不胜感激!
解决方法
由于您尚未发布代码,因此我无法评论这是否是最佳方法。但是您问题的答案是是。
让我首先总结一下您要实现的目标(我理解):您有几个对象(网格单元格或其坐标)。您还具有一个为每个对象分配优先级的映射。现在,您需要建立一个优先级队列,该队列根据地图中的优先级对对象进行排序。
可以通过将自定义Comparator
输入优先级队列来实现。比较器获取对象(在我们的示例中为两个网格单元),然后返回两个中较小的一个(或在优先级队列的概念中优先出现)。我们的特殊比较器将需要使用组合数量访问Map
。一旦具有此访问权限,比较两个GridCell
就很容易了。这是合作者:
class GridCellComparer implements Comparator<GridCell> {
// reference to the map with the number of combinations for each grid cell
Map<GridCell,Integer> combinations;
public GridCellComparer(Map<GridCell,Integer> combinations) {
this.combinations = combinations;
}
// calculate which grid cell comes first
public int compare(GridCell c1,GridCell c2) {
return combinations.get(c2) - combinations.get(c1);
}
}
要使用此比较器,我们需要使用PriorityQueue
的{{1}}的构造函数重载。这种过载也会占用初始容量,我们可以将其设置为要添加的电池数量:
Comparator
其余部分与其他任何优先级队列一样工作。您添加网格单元,依此类推。这是一个完整的例子。代码的第一部分生成一些网格单元,并为它们设置许多组合。网格单元格中的PriorityQueue<GridCell> prio = new PriorityQueue<GridCell>(cells.size(),new GridCellComparer(combinations));
仅在打印它们时用于识别它们。
int n
运行此代码时,将看到以下输出:
import java.util.Map;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
public class Example {
public static void main(String []args){
// map with the number of combinations for each cell
Map<GridCell,Integer> combinations = new HashMap<GridCell,Integer>();
// list of grid cells
List<GridCell> cells = new ArrayList<GridCell>();
for(int i = 0; i < 5; ++i)
cells.add(new GridCell(i));
// add number of combinations for each grid cell
combinations.put(cells.get(0),2);
combinations.put(cells.get(1),0);
combinations.put(cells.get(2),6);
combinations.put(cells.get(3),4);
combinations.put(cells.get(4),10);
// instantiate the priority queue
PriorityQueue<GridCell> prio = new PriorityQueue<GridCell>(cells.size(),new GridCellComparer(combinations));
prio.addAll(cells);
// retrieve the grid cells in the order imposed by the number of combinations
while(!prio.isEmpty()) {
GridCell topCell = prio.poll();
System.out.println(topCell);
}
}
}
class GridCell{
// number to identify the cell
private int n;
public GridCell(int n) { this.n = n; }
public String toString(){
return Integer.toString(n);
}
}
class GridCellComparer implements Comparator<GridCell> {
// reference to the map with the number of combinations for each grid cell
Map<GridCell,GridCell c2) {
return combinations.get(c2) - combinations.get(c1);
}
}
这些是GridCell id,从高数量的组合到低数量的顺序。