algorithm - 查找2个节点之间是否存在路径深度优先搜索

标签 algorithm data-structures graph binary-tree depth-first-search

我正在使用深度优先搜索和图表来查找 2 个节点之间是否存在路径。 但出于某种原因,即使存在路径,我的方法也总是返回错误。

这是我的搜索代码:

static boolean search(Graph g, Node start, Node end)
{

if(start == null || end == null) return false;

start.state = State.Visited;

for(Node u: start.getChildNodes())
{
    if(u.state != State.Visited)
    {
        if(u.equals(end))
        {
            return true;
        }
        else
        {
            u.state = State.Visited;
            search(g,u,end);
        }
    }
}

return false;

我这样调用方法:

public static void main(String[] args) {

        Graph gDfs = createNewGraph();

        System.out.println("path between A & B");
        System.out.println(search(gDfs,gDfs.getNode()[0],gDfs.getNode()[1]));
    }

createNewGraph()

public static Graph createNewGraph()
{

Graph g = new Graph();        
Node[] temp = new Node[8];

temp[0] = new Node("A", 3);
temp[1] = new Node("B", 3);
temp[2] = new Node("C", 1);
temp[3] = new Node("D", 1);
temp[4] = new Node("E", 1);
temp[5] = new Node("F", 1);

temp[0].addChildNode(temp[1]);
temp[0].addChildNode(temp[2]);
temp[0].addChildNode(temp[3]);

temp[1].addChildNode(temp[0]);
temp[1].addChildNode(temp[4]);
temp[1].addChildNode(temp[5]);

temp[2].addChildNode(temp[0]);
temp[3].addChildNode(temp[0]);
temp[4].addChildNode(temp[1]);
temp[5].addChildNode(temp[1]);

for (int i = 0; i < 7; i++) 
{
    g.addNode(temp[i]);
}
return g;

@amit => 这是你的建议吗?

for(Node u: start.getChildNodes())
        {
            if(u.state != State.Visited)
            {
                if (search(g,u,end)) return true;
            }
        }

最佳答案

最好只使用当前状态,而不是下一个或上一个(无论是 dfs 还是 bfs)。

boolean search(Graph g, Node current, Node target)
{

    if (current == null || target == null) return false;

    current.state = State.Visited;

    if (current == target) return true;

    for(Node u: current.getChildNodes())
    {
        if(u.state != State.Visited && search(g,u,target))
        {                
            return true;
        }
    }    
    return false;    
}

并且某些顶点的“状态”可能未标记为“State.Visited”,即使它可以从“A”实现。它可能会导致一些错误,或错误的复杂性估计。我建议检查最坏的情况

void search(Graph g, Node v)
{
    v.state = State.Visited;     

    for(Node u: v.getChildNodes())
    {
        if(u.state != State.Visited)
        {                
            search(g,u);
        }
    }        
}

并检查“B.state”是否为“State.Visited”

关于algorithm - 查找2个节点之间是否存在路径深度优先搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23441794/

相关文章:

c - 提高效率 "lighthouse"

c# - 哈希表在调整大小时如何跟踪现有的键索引?

Matlab 内线捕捉

algorithm - 在给定顶点和一些限制的情况下查找图中的所有路径

algorithm - 如何在具有硬限制的函数上计算大 O?

Java数组算法-大O

python - 在 Python 中解析化学公式

algorithm - 运行时的渐近符号

arrays - 随机访问数组的时间复杂度

r - R : plot & the result is “plot.new has not been called yet”