Algorithm.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace DrawGraph
  7. {
  8. public class Algorithm
  9. {
  10. private static int MinDistance(int[] path, bool[] includedToPath, int n)
  11. {
  12. // Initialize min value
  13. int min = int.MaxValue, min_index = -1;
  14. for (int v = 0; v < n; v++)
  15. if (includedToPath[v] == false && path[v] <= min)
  16. {
  17. min = path[v];
  18. min_index = v;
  19. }
  20. return min_index;
  21. }
  22. public static int DijkstraCount(int[,] adjacencyMatrix, int startIndex, int finishIndex)
  23. {
  24. int n = adjacencyMatrix.GetLength(0);
  25. int[] path = new int[n];
  26. bool[] includedToShortestPath = new bool[n];
  27. for (int i = 0; i < n; i++)
  28. {
  29. path[i] = int.MaxValue;
  30. includedToShortestPath[i] = false;
  31. }
  32. path[startIndex] = 0;
  33. for (int i = 0; i < n - 1; i++)
  34. {
  35. int min = MinDistance(path, includedToShortestPath, n);
  36. includedToShortestPath[min] = true;
  37. for (int j = 0; j < n; j++)
  38. {
  39. if (!includedToShortestPath[j] && adjacencyMatrix[min, j] != 0 &&
  40. path[min] + adjacencyMatrix[min, j] < path[j])
  41. {
  42. path[j] = path[min] + adjacencyMatrix[min, j];
  43. }
  44. }
  45. }
  46. return path[finishIndex];
  47. }
  48. public static LinkedList<Node> DepthSearch(Node[] node, Edge[] edge, int sourceIndex, int targetIndex)
  49. {
  50. var visited = new HashSet<Node>();
  51. var path = new LinkedList<Node>();
  52. Dfs(node[sourceIndex], node[targetIndex], visited, path, edge);
  53. if (path.Count > 0)
  54. path.AddFirst(node[sourceIndex]);
  55. return path;
  56. }
  57. private static bool Dfs(Node node, Node goal,HashSet<Node> visited, LinkedList<Node> path, Edge[] edges)
  58. {
  59. if (Node.Compare(node, goal))
  60. return true;
  61. visited.Add(node);
  62. foreach(var edge in edges.Where(x=>!visited.Contains(x.SourceNode) || !visited.Contains(x.TargetNode)))
  63. {
  64. if(Dfs(edge.TargetNode, goal, visited, path, edges))
  65. {
  66. path.AddFirst(edge.TargetNode);
  67. return true;
  68. }
  69. }
  70. return false;
  71. }
  72. }
  73. }