/// <summary> /// Get the topological order /// </summary> /// <param name="orderedStrings">the ordered ingredients</param> /// <param name="n">the number of ingredients</param> public static string GetTopologicalOrder(string[][] orderedStrings, int n) { var dic = new Dictionary <string, int>(); var list = new List <string>(); var g = CreateListArray <int>(n); int v = 0; foreach (var item in orderedStrings) { if (!dic.ContainsKey(item[0])) { dic[item[0]] = v++; list.Add(item[0]); } if (!dic.ContainsKey(item[1])) { dic[item[1]] = v++; list.Add(item[1]); } g[dic[item[0]]].Add(dic[item[1]]); } if (CycleDirectedGraph.DoesGraphContainsCycle(g)) { return("KO"); } var stack = TopologicalSorting.GetSortingOrder(g); return(string.Join(" ", stack.Select(s => list[s]))); }
public void CycleDirectedGraph_Returns_False() { // Arrange var graph = GraphBuilderHelper.CreateListArray(5); graph[0].Add(1); graph[0].Add(2); graph[3].Add(0); graph[4].Add(0); // Act bool result = CycleDirectedGraph.DoesGraphContainsCycle(graph); // Assert Assert.IsFalse(result); }