无法在C#中实现递归生成器

时间:2017-05-08 10:58:19

标签: c# recursion generator ienumerable

你好!我想在C#中实现这个递归生成器,我不明白它为什么不返回任何东西。它是深度优先搜索算法,提供2点之间的所有可能路径。

using System;
using System.Collections;
using System.Collections.Generic;

namespace ConvertDfsFromPython
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            List<string> a = new List<string> ();
            List<string> b = new List<string> ();
            List<string> e = new List<string> ();
            List<string> f = new List<string> ();
            List<string> c = new List<string> ();
            List<string> d = new List<string> ();
            List<string> g = new List<string> ();


            a.Add ("f");
            a.Add ("b");
            a.Add ("c");

            b.Add ("c");
            b.Add ("d");
            b.Add ("e");
            b.Add ("f");

            e.Add ("c");
            e.Add ("d");
            e.Add ("f");

            d.Add ("g");
            d.Add ("f");


            Dictionary<string, List<string>> graph = new Dictionary<string, List<string>> ();

            graph.Add ("a", a);
            graph.Add ("b", b);
            graph.Add ("c", c);
            graph.Add ("d", d);
            graph.Add ("e", e);
            graph.Add ("f", f);
            graph.Add ("g", g);



            MainClass myMainClass = new MainClass();

            IEnumerable<List<string>> getPath = myMainClass.dfsPath(graph, "a", "f");

            foreach (List<string> path in getPath) {
                foreach(string pathElement in path){
                    Console.WriteLine (pathElement);
                }
            }



        }

        public IEnumerable<List<string>> dfsPath(Dictionary<string, List<string>> graph, string root, string target, List<string> path = null){

            if(path == null){

                path = new List<string> ();
                path.Add (target);


            }

            if(root == target){
                yield return path;

                foreach (string element in path) {
                    Console.WriteLine (element);
                }
            }

            foreach(string vertex in graph[root]){

                if (!path.Contains(vertex)){

                    path.Add (vertex);

                    foreach(List<string> eachPath in dfsPath(graph, vertex, target, path )) {
                        yield return eachPath;

                    }
                }

            }
        }

    }
}

0 个答案:

没有答案