广度优先搜索定向邻接列表以查找所有路径

时间:2016-12-08 13:27:28

标签: c# .net

对于自学,我试图从包含有向图的邻接列表中找到所有可能的路径(具有可能的权重约束)。

我的图表在对象Dictionary<City, List<Node>>中 含有例如

City.A, {(City.B;5),(City.C;2),(City.D;5)}
City.B, {(City.D;8),(City.A;2)}
.....

目标是尝试查找从city1到city2的所有路径,这些路径可以在精确的X跳中到达。

我的广度优先搜索方法没有给出正确的回程:

 class IterateAllPaths
{



    public List<Trip> bfs(AdjacencyList graph, City from, City to, int allowedHops)
    {

        Queue<City> searchQ = new Queue<City>();
        searchQ.Enqueue(from);
        List<Trip> trips = new List<Trip>();
        List<Trip> allTrips = new List<Trip>();

        City currentCity;

        trips.Add(new Trip());

        int tripsCounter = 0;
        int QIndex = 0;
        int hops = 0;
        int maxNumOfHops = allowedHops;

        int[] lastLevels = new int[maxNumOfHops + 1];
        lastLevels[hops] = 1;

        while (searchQ.Count != 0)
        {
            lastLevels[hops]--;
            currentCity = searchQ.Dequeue();

            if (trips[tripsCounter].Cities == null)
            {
                List<City> cities = new List<City>();
                cities.Add(currentCity);
                trips[tripsCounter].Cities = cities;
            }
            else
            {
                trips[tripsCounter].Cities.Add(currentCity);
            }
            if (currentCity == to && QIndex > 0 && hops == maxNumOfHops)
            {
                //this contains all trips
                allTrips.Add(trips[tripsCounter]);
            }

            if ((hops + 1) <= maxNumOfHops)
            {

                Dictionary<City, List<Node>> myGraph = graph.GetGraph;

                List<Node> neighbors = myGraph[currentCity];

                foreach (Node neighbor in neighbors)
                {
                    searchQ.Enqueue(neighbor.CityName);
                }

                lastLevels[hops + 1] += neighbors.Count;

                while (trips.Count < lastLevels[hops + 1])
                {
                    trips.Add(new Trip());
                }

            }

            tripsCounter++;
            if (lastLevels[hops] == 0)
            {
                hops++;
                tripsCounter = 0;
            }
            QIndex++;
        }
        return allTrips;



    }

}

public class Trip
{

    public List<City> Cities
    {

        get;
        set;

    }
}

0 个答案:

没有答案