检查节点是否直接连接到特定节点

时间:2018-10-03 16:18:29

标签: c# search nodes root path-finding

我希望能够检查特定节点是否直接或间接连接到根节点。下面的代码在某种程度上可以正常工作,但是常常无法找到根(在显而易见的情况下)。

编辑:本文中使用词root并不表示任何保留术语,而只是布尔变量的自发名称,该布尔变量将节点标记为“特殊”。

到目前为止:

//The node
public class Node
{
    public Node[] connectedNodes;
    public bool rootNode;
}

//The function
public static bool HasRootNode(Node fromNode)
{
    List<Node> Processed = new List<Node>();
    Stack<Node> WorkStack = new Stack<Node>(FromNode.connectedNodes);

    Processed.Add(fromNode);

    while (WorkStack.Count != 0)
    {
        Node workItem = WorkStack.Pop();

        foreach (Node cNode in workItem.connectedNodes)
        {
            if (Processed.Contains(cNode))
                continue;

            if (cNode.rootNode)
                return true; // Found..

            WorkStack.Push(cNode); // Queue all of the connectedNodes for this node
            Processed.Add(cNode); // This node has been processed..
        }
    }

    return false; // Not found..
}

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

对不起,我只检查workItem的子节点,而不检查workItem节点本身。 :)

感谢您的时间和精力!

//The node
public class Node
{
    public Node[] connectedNodes;
    public bool rootNode;
}

//The function
public static bool HasRootNode(Node fromNode)
{
    List<Node> Processed = new List<Node>();
    Stack<Node> WorkStack = new Stack<Node>(FromNode.connectedNodes);

    Processed.Add(fromNode);

    while (WorkStack.Count != 0)
    {
        Node workItem = WorkStack.Pop();
        if (workItem.rootNode)
            return true; // Found..

        foreach (Node cNode in workItem.connectedNodes)
        {
            if (Processed.Contains(cNode))
                continue;

            if (cNode.rootNode)
                return true; // Found..

            WorkStack.Push(cNode); // Queue all of the connectedNodes for this node
            Processed.Add(cNode); // This node has been processed..
        }
    }

    return false; // Not found..
}