0

我想生成一个 DAG(有向无环图)的 BFS 森林。这意味着我的 Tree 类需要是通用树而不是二叉树(换句话说,当我生成森林时,我无法提前知道节点将拥有的子节点数量)。大部分代码都编写并显示在下面,但是我缺少一行代码,这对我来说是一辈子的事!

public Tree BFS(V start)
{
    reset();
    LinkedList<GraphMatrixVertex<V>> list = new LinkedList<GraphMatrixVertex<V>>();
    GraphMatrixVertex<V> vert = dict.get(start);
    Tree root = new Tree(vert); 
    list.add(vert);
    do
    {
        vert = list.getFirst();
        Iterator<V> ni = neighbors(start);
        while(ni.hasNext())
        {
            V v = ni.next();
            GraphMatrixVertex<V> vtx = dict.get(v);
            if(!vtx.isVisited())
            {
                list.add(vtx);
                            vtx.visit();
                root.addChild(new Tree(vtx));
            }
        }
    //code goes here
    }
    while(!list.isEmpty());

    return root;
}

我的 Tree 类存储一个值参数、一个父引用和一个子列表。我的问题是引用下一个树节点。将所有未访问的邻居添加为当前节点的子节点后,如何到达下一个节点?

编辑:

所以它看起来像这样?

public void bfs(Tree parent)
{   
    Iterator<V> ni = neighbors((V) parent.value());
    if(ni.hasNext())
    {
            while(ni.hasNext())
            {
            V next = ni.next();
            GraphMatrixVertex<V> vert = dict.get(next);
            if(!vert.isVisited())
                parent.addChild(new Tree(next));
        }   
    }
}

递归调用在哪里?

4

1 回答 1

1

如果我正确理解您的问题,您可以为此使用递归。基本上,您有一个创建一层节点的函数,然后为您要创建/访问的每个子节点再次调用自身。

编辑:

好的,我稍微编辑了您的代码。首先,我删除了 if(hasNext) 作为其中的 while 循环的冗余。对于邻居列表上的每个子节点,您创建一个新的树节点,然后运行它的 bfs() 方法,将当前的 Tree 对象传入。该函数返回一个列表,它应该是通过树的最佳路径。我也不确定您获取相邻节点的方式,它看起来有点奇怪。我也没有测试过代码,所以其中可能存在拼写错误和其他内容,但希望它能让您了解如何进行搜索。哦,当你点击一个叶节点(你的目标?)时,它只需要设置它的权重并返回一个只有它自己的新列表。

int weight; // this should be you node traversal cost

public LinkedList<Tree> bfs(Tree parent){

    Iterator<V> ni = neighbors((V) parent.value());

    LinkedList bestPath = null;       
    int bestScore = 0xFFFFFFFF;

    while(ni.hasNext()){
        V next = ni.next();
        GraphMatrixVertex<V> vert = dict.get(next);
        if(!vert.isVisited()){
            Tree newNode = new Tree(next);
            parent.addChild(newNode);
            LinkedList path = newNode.bfs(this);
                if(newNode.weight < bestScore){
                    bestScore = weight;
                    bestPath = path;
                }
        }
    }
    weight = bestScore + this.weight;
    bestPath.addFirst(this);
    return path;   
}

编辑2:

public void bfs(Tree parent){

    Iterator<V> ni = neighbors((V) parent.value());

    while(ni.hasNext()){
        V next = ni.next();
        GraphMatrixVertex<V> vert = dict.get(next);
        if(!vert.isVisited()){
            Tree newNode = new Tree(next);
            parent.addChild(newNode);
            newNode.bfs(this);
        }
    }
}
于 2010-08-18T08:23:25.137 回答