递归树搜索返回错误结果

时间:2015-06-28 10:59:51

标签: c# algorithm recursion

我有this implementation树递归函数。它获得了从A到D的所有可能路径。

递归函数是:

private static List<Path> GetPath(int depth, Path path)
{
    if (depth == nodes.Length) 
    {
        return new List<Path> { path };
    }
    else 
    {
        var result = new List<Path>();
        foreach(var link in nodes[depth].Links)
        {
            Node node = new Node { Name = nodes[depth].Name, Links = new[] { link } };
            path.Add(node);

            result.AddRange(
                GetPath(
                    depth+1, path));
        }

        return result;
    }
}

预期结果应为:

A1-B2->C3->D4
A1-B5->C3->D4

但是,返回的路径是相同的,它们包括所有可能的节点两次。

该功能出了什么问题?

2 个答案:

答案 0 :(得分:1)

foreach(var link in nodes[depth].Links)
{
    Node node = new Node { Name = nodes[depth].Name, Links = new[] { link } };
    path.Add(node);

您可能打算在附加下一个节点之前为此处找到的每个节点创建一个新路径(这是path的副本)。

答案 1 :(得分:1)

正如@ moreON&#39建议的那样,我将克隆函数添加到类Path中,并修改循环,在循环中复制到新的路径实例:

public class Path : List<Node>
{
    public override string ToString()
    {
        String s = "";

        foreach (var node in this)
        {
            s += node.Name + node.Links[0] + "->";
        }
        return s;
    }

    public Path Clone()
    {
        var newPath = new Path();
        ForEach(x => newPath.Add(new Node {Name = x.Name, Links = new int[] {x.Links[0]}}));
        return newPath;
    }
}

    private static List<Path> GetPath(int depth, Path path)
    {
        if (depth == nodes.Length)
        {
            return new List<Path> { path };
        }
        else
        {
            var result = new List<Path>();

            foreach (var link in nodes[depth].Links)
            {
                Node node = new Node { Name = nodes[depth].Name, Links = new[] { link } };
                var currentPath = path.Clone();
                currentPath.Add(node);

                result.AddRange(GetPath(depth + 1, currentPath));
            }
            return result;
        }
    }

希望得到这个帮助。