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

问题描述 投票:0回答:1

我希望能够检查特定节点是否直接或间接连接到根节点。下面的代码在某种程度上有效,但经常无法找到根(当它很明显应该找到根时)。

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

到目前为止:

//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..
}

感谢任何帮助!

c# search nodes root path-finding
1个回答
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..
}
© www.soinside.com 2019 - 2024. All rights reserved.