【发布时间】:2013-03-18 15:08:32
【问题描述】:
这是我现在使用 HashMap 实现的方法
private int steps=0;
private LinkedList<MazeCell> breadCrumbs = new LinkedList<MazeCell>();
private HashMap<MazeCell, Boolean> visitedCells = new HashMap<MazeCell, Boolean>();
public int stepsToSolveMaze(MazeCell cell)
{
if (visitedCells.get(cell) == null)
{
visitedCells.put(cell, true);
breadCrumbs.push(cell);
}
我正在使用递归算法来查找迷宫终点的步数。在我尝试迈出下一个“步骤”之前,我需要确保我没有去过我要迈出的地方。我觉得除了我去过的地方之外,还有比充满空值的 HashMap 更好的数据结构,但我真的不知道。有谁知道更好的数据结构吗?
【问题讨论】:
-
我觉得 Set 是不错的选择。
-
迷宫中有环路吗?
-
我会在阅读后同意,但我选择 HashMap 是因为假设迷宫是 1000x1000,我可以在相对恒定的时间内知道我是否去过那里,因为我会有一个答案,而不是遍历整个列表。然后我阅读了更多内容,看到了 HashSet,它使用 HashMap 来做我正在做的事情,但更漂亮!谢谢!
-
@BrandonRossPollack 您可以使用方法 set.contains("something");检查您是否已经访问过该节点。
-
图形数据结构听起来是最适合您的结构。
标签: java data-structures hashmap depth-first-search