public static List<List<PathStop>> getAllPossiblePathsBetweenTwoPoints(Dictionary<int, Dictionary<int, decimal>> adjListWithWeight, int startSID, int endSID) { List<List<int>> paths = new List<List<int>>(); List<List<int>> visitedPaths = new List<List<int>>(); List<List<int>> nextPaths = new List<List<int>>(); //initiate visitedPaths.Add(new List<int>()); visitedPaths[0].Add(startSID); //bug: evaluate the while condition while (visitedPaths.Count!=0) { foreach (List<int> path in visitedPaths) { foreach (int u in adjListWithWeight[path.Last()].Keys) { int[] pathToArray = new int[path.Count]; path.CopyTo(pathToArray);//make a deep copy of the object List<int> pathClone = pathToArray.ToList(); if (u == endSID) { pathClone.Add(u); paths.Add(pathClone); } else { if (!path.Contains(u)) //exclude loop situation { pathClone.Add(u); nextPaths.Add(pathClone); } } } } visitedPaths = nextPaths; nextPaths = new List<List<int>>(); } Dictionary<List<int>, decimal> pathWithWeight = new Dictionary<List<int>, decimal>(); if (paths.Count!=0) { foreach (List<int> path in paths) { decimal totalWeight = 0; for (int i = 0; i < path.Count; i++) { if (i!=0) { totalWeight += adjListWithWeight[path[i-1]][path[i]]; } } pathWithWeight.Add(path, totalWeight); } } pathWithWeight = pathWithWeight.OrderBy(i => i.Value).ToDictionary(x => x.Key, x => x.Value); List<List<int>> sorted = pathWithWeight.Keys.ToList(); //build the ordered paths List<List<PathStop>> sortedPaths = new List<List<PathStop>>(); for (int i = 0; i < sorted.Count; i++) { List<PathStop> path = new List<PathStop>(); for (int j = 0; j < sorted[i].Count; j++) { if (path.Count==0) { PathStop ps = new PathStop() {stationID = sorted[i][j], driveHour = 0}; path.Add(ps); } else { PathStop ps = new PathStop() { stationID = sorted[i][j], driveHour = path[path.Count-1].driveHour + adjListWithWeight[sorted[i][j - 1]][sorted[i][j]] }; path.Add(ps); } } sortedPaths.Add(path); } return sortedPaths; }
public static List<PathStop> buildRoute(Dictionary<int, decimal> visitedStationIDs_distance, Dictionary<int, int> stationID_parentID, int endSID) { List<PathStop> route = new List<PathStop>(); int parentId = endSID; while (parentId!=0) { PathStop stop = new PathStop() { stationID = parentId, driveHour = visitedStationIDs_distance[parentId] }; route.Add(stop); parentId = stationID_parentID[parentId]; } route.Reverse(); return route; }
//return a path consists of station id and drivehour from each station to start station. public static List<PathStop> buildRoute(List<FibonacciNode> S, int endSID) { List<PathStop> route = new List<PathStop>(); FibonacciNode endNode = S.Find(node => node.StationID == endSID); FibonacciNode lastStop = endNode; while (lastStop != null) { PathStop stop = new PathStop() { stationID = lastStop.StationID, driveHour = lastStop.MinPathValue }; route.Add(stop); lastStop = lastStop.lastStop; } route.Reverse(); return route; }