/// <summary> /// Алгоритм Джонсона. Сложность 0(V^2*lgV + VE), если Фибоначчиевая куча, или 0(VE*lgV). /// Вычисление кратчайших путей между всеми парами вершин /// </summary> public string JohnsonAlgorithm() { Size += 1; VerticesList.Add(new Vertex(Size)); Vertex curVertexFrom = VerticesList[Size - 1]; for (int i = 0; i < Size - 1; i++) { Vertex curVertexTo = VerticesList[i]; IncidentEdge curEdge = new IncidentEdge(curVertexTo, 0); curVertexFrom.AdjacencyList.Add(curEdge); } if (BellmanFordAlgorithm(curVertexFrom) == false) { Console.WriteLine("Входной граф содержит цикл с отрицательным весом"); } else { foreach (var vertex in VerticesList) { foreach (var incidentEdge in vertex.AdjacencyList) { incidentEdge.Weight = incidentEdge.Weight + vertex.Distance - incidentEdge.IncidentTo.Distance; } } VerticesList.RemoveAt(Size - 1); Size -= 1; int[] Distances = new int[Size]; for (int i = 0; i < Size; i++) { Distances[i] = VerticesList[i].Distance; } int[,] matrix = new int[Size, Size]; for (int i = 0; i < Size; i++) { Dijkstra(VerticesList[i]); for (int j = 0; j < Size; j++) { matrix[i, j] = VerticesList[j].Distance + Distances[j] - Distances[i]; } } StringBuilder output = new StringBuilder(); for (int i = 0; i < Size; i++) { for (int j = 0; j < Size; j++) { output.Append(matrix[i, j] + " "); } output.Append("\n"); } Console.WriteLine(output); return(output.ToString()); } return(null); }
public Graph(int size, string[] strs) { Size = size; VerticesList = new List <Vertex>(); for (int i = 1; i <= Size; i++) { VerticesList.Add(new Vertex(i)); } try { int curIndex = 0; foreach (var str in strs) { Vertex curVertexFrom = VerticesList[curIndex]; var array = str.Split(); int length = array.Length; if (!string.IsNullOrEmpty(str)) { for (int i = 0; i < length; i++) { int intVar = int.Parse(array[i++]); if (intVar > Size) { throw new Exception("The vertex is missing"); } Vertex curVertexTo = VerticesList[intVar - 1]; intVar = int.Parse(array[i]); IncidentEdge curEdge = new IncidentEdge(curVertexTo, intVar); curVertexFrom.AdjacencyList.Add(curEdge); } } curIndex += 1; } } catch (Exception ex) { if (ex is NullReferenceException || ex is FormatException) { Console.WriteLine("String is empty (Graph)"); //throw new Exception("String is empty (Graph)"); } else { throw new Exception(ex.Message); } } }