Guest User

Untitled

a guest
Apr 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package graphs;
  6.  
  7. /**
  8. *
  9. * @author David
  10. */
  11. public class Floyd
  12. {
  13. private int[][] m_graph;
  14. private int[][] m_next;
  15. private int[][] m_path;
  16.  
  17. private static int INFINITY = 9999999;
  18.  
  19. public Floyd(int n)
  20. {
  21. m_graph = new int[n][n];
  22. m_next = new int[n][n];
  23. m_path = new int[n][n];
  24.  
  25. createSampleGraph();
  26. }
  27.  
  28. public void floyd()
  29. {
  30. init();
  31. int n = m_graph.length;
  32. for(int k = 0; k < n; ++k)
  33. for(int v = 0; v < n; ++v)
  34. for(int w = 0; w < n; ++w)
  35. if(m_path[v][k] + m_path[k][w] < m_path[v][w])
  36. {
  37. m_path[v][w] = m_path[v][k] + m_path[k][w];
  38. m_next[v][w] = k;
  39. }
  40.  
  41. }
  42.  
  43. public void print(int source, int end)
  44. {
  45. int k = m_next[source][end];
  46. if(k != -1)
  47. {
  48. print(source, k);
  49. System.out.println(k);
  50. print(k, end);
  51. }
  52. }
  53.  
  54. private void init()
  55. {
  56. int n = m_graph.length;
  57. for(int v = 0; v < n; ++v)
  58. for(int w = 0; w < n; ++w)
  59. {
  60. m_path[v][w] = m_graph[v][w];
  61. m_next[v][w] = -1;
  62. }
  63. }
  64.  
  65. private void createSampleGraph()
  66. {
  67. for(int i = 0; i < m_graph.length; ++i)
  68. for(int j = 0; j < m_graph.length; ++j)
  69. {
  70. if(i == j)
  71. m_graph[i][j] = 0;
  72. else
  73. m_graph[i][j] = INFINITY;
  74. }
  75.  
  76. m_graph[0][1] = 10;
  77. m_graph[0][4] = 100;
  78. m_graph[0][3] = 30;
  79. m_graph[1][2] = 50;
  80. m_graph[2][4] = 10;
  81. m_graph[3][2] = 20;
  82. m_graph[3][4] = 60;
  83. }
  84. }
  85.  
  86. /*
  87. Gebruik
  88. */
  89. public class Backtracking {
  90.  
  91. /**
  92. * @param args the command line arguments
  93. */
  94. public static void main(String[] args)
  95. {
  96. Floyd f = new Floyd(5);
  97. f.floyd();
  98. f.print(0, 4);
  99.  
  100. }
  101. }
Add Comment
Please, Sign In to add comment