【问题标题】:DFS Java implementation: how to write "Element in deque/stack"DFS Java 实现:如何编写“双端队列/堆栈中的元素”
【发布时间】:2013-12-27 07:13:16
【问题描述】:

我在 DFS java 实现中卡在一行中间:如何表达“双端队列/堆栈中的顶点?”

我需要在for循环中写一行来表示顶点“u”在双端队列/堆栈中。初始值为“toExplore”的第一项。

下面是我的代码:

public List<Integer> DepthFirstList(Integer v)
{
    List<Integer> vertices = new ArrayList<Integer>(); 
    Deque<Integer> toExplore = new ArrayDeque<Integer>(); //The deque,used as the stack in DFS
    List<Integer> visited = new ArrayList<Integer>();
    toExplore.push(v);
    visited.add(v);
    while(!toExplore.isEmpty())
    {
        boolean hasNeighbor=false;
        for()//To be more precise, u should be a vertex never visited. How can I make this change?
        {
            if(g.hasEdge(v, u)) 
            {
                toExplore.push(u);
                visited.add(u);
                hasNeighbor=true;
                break;
            }

        }
        if(hasNeighbor==false) 
        {
            toExplore.pop();
            vertices.add(v);
        }
        else hasNeighbor=false;
    }
    return vertices;
}

【问题讨论】:

  • v = toExplore.pop(),然后从v 开始循环。是否有某种getAllEdgesgetAllNeighbours 功能?
  • 你最好维护一个单独的Set 访问的顶点。
  • @Dukeling 有一个名为TreeMap&lt;Integer,Integer&gt; getAdjList(Integer v) 的函数,它返回特定顶点的邻接列表。
  • TreeMap 究竟包含什么?我认为v,u 对应每个邻居u,但这不可能,因为每个条目都会相互覆盖(因为它是Map)。
  • @Dukeling 只有一行代码return adjList.get(v)adjList 是一个私有变量,定义为 adjList = new ArrayList&lt;TreeMap&lt;Integer, Integer&gt;&gt;(); for (int i=0; i&lt;numVertices; i++) { adjList.add(new TreeMap&lt;Integer, Integer&gt;());

标签: java algorithm stack depth-first-search


【解决方案1】:

用下面的替换你的for循环应该可以工作:

v = toExplore.peek();
for (int u: getAdjList(v).keySet())
{
   if (!visited.contains(u))
   {
      ...
   }
}

似乎邻接列表包含另一个顶点索引到边权重的映射,因此keySet 将为我们提供所有顶点的列表。

一些随机笔记:

  • 如果允许,我会推荐一种递归方法。一旦你了解了递归,它就会简单得多(从长远来看,这绝对是一件让你感到舒服的好事情)。但是以非递归方式编写递归算法无疑是一种很好的编程习惯。

  • 正如 Louis 所说,如果可以的话,将 visited 设置为 Set (HashSet) 会好得多。这将允许预期的O(1)(恒定时间)查找,而不是O(n)(线性时间)。

  • 另外,我可能会将toExplore 设为Stack,因为您只会使用基于堆栈的方法。

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 2016-08-18
    • 1970-01-01
    • 2016-04-16
    • 2013-03-10
    • 2018-07-27
    • 2021-07-08
    • 2011-06-23
    • 2018-08-10
    相关资源
    最近更新 更多