private static int[] TopologicalSorting(GraphAdjAlt0 g) { int n = g.v.Length; marked = new int[n]; reversePost = new Stack<int>(); for (int v = 0; v < n; v++) { if (marked[v] != 0) { continue; } DFS(g, v); } int[] r = new int[reversePost.Count]; int i = 0; while (reversePost.Count != 0) { r[i] = reversePost.Pop() + 1; i++; } return r; }
public DataDirectedGraphsAlt0(string fileName) { string filePath = Utils.GetFullFilePath(fileName); try { using (StreamReader reader = new StreamReader(filePath)) { string line; int iGraph = -1; int countVerticles; int countEdges = 0; line = reader.ReadLine(); Count = int.Parse(line); Graphs = new GraphAdjAlt0[Count]; while ((line = reader.ReadLine()) != null) { if (line == "") { continue; } if (countEdges == 0) { iGraph++; string[] args = line.Split(' '); countVerticles = int.Parse(args[0]); countEdges = int.Parse(args[1]); Graphs[iGraph] = new GraphAdjAlt0(); Graphs[iGraph].v = new List<int>[countVerticles]; for (int i = 0; i < Graphs[iGraph].v.Length; i++) { Graphs[iGraph].v[i] = new List<int>(); } continue; } string[] edge = line.Split(' '); int v0 = int.Parse(edge[0]) - 1; int v1 = int.Parse(edge[1]) - 1; Graphs[iGraph].v[v0].Add(v1); countEdges--; } } } catch (Exception e) { Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } }
private static int[] HamiltonianPath(GraphAdjAlt0 g) { int[] r = TopologicalSorting(g); // next vertix (with index i + 1) must finding in // list of previous vertix (with index i), becouse must be edge // beetween them for(int i = 0; i < r.Length - 1; i++) { if (g.v[r[i] - 1].IndexOf(r[i + 1] - 1) == -1) { return new int[] { -1 }; } } int[] rr = new int[r.Length + 1]; Array.Copy(r, 0, rr, 1, r.Length); rr[0] = 1; return rr; }
private static void DFS(GraphAdjAlt0 g, int v) { marked[v] = 1; if (null != g.v[v]) { foreach (int i in g.v[v]) { if (marked[i] != 0) { continue; } DFS(g, i); } } reversePost.Push(v); }