fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. public class Main {
  6. public static void main(String[] args) {
  7. Graph graph = new Graph();
  8.  
  9. graph.addVertex('A'); // 0
  10. graph.addVertex('B'); // 1
  11. graph.addVertex('C'); // 2
  12. graph.addVertex('D'); // 3
  13. graph.addVertex('E'); // 4
  14. graph.addVertex('F'); // 5
  15. graph.addVertex('G'); // 6
  16.  
  17. graph.addEdg(0, 1, 3);
  18. graph.addEdg(0, 2, 5);
  19. graph.addEdg(0, 3, 7);
  20. graph.addEdg(1, 4, 6);
  21. graph.addEdg(2, 4, 4);
  22. graph.addEdg(2, 3, 3);
  23. graph.addEdg(3, 5, 3);
  24. graph.addEdg(4, 6, 6);
  25. graph.addEdg(5, 6, 4);
  26.  
  27. //graph.printRelationMatrix();
  28. graph.path();
  29.  
  30. }
  31. }
  32.  
  33. class Graph{
  34. private final int MAX_VERTS = 7;
  35. private final int INFINITY = 100000000;
  36. private Vertex vertexList[];
  37. private Integer relationMatrix[][];
  38. private int countOfVertices;
  39. private int countOfVertexInTree;
  40. private List<Path> shortestPaths; //список данных кратчайших путей
  41. private int currentVertex;
  42. private int startToCurrent; //расстояние до currentVertex
  43.  
  44. public Graph(){
  45. vertexList = new Vertex[MAX_VERTS];
  46. relationMatrix = new Integer[MAX_VERTS][MAX_VERTS];
  47. countOfVertices = 0;
  48. countOfVertexInTree = 0;
  49. for(int i=0; i<MAX_VERTS; i++){
  50. for(int k=0; k<MAX_VERTS; k++){
  51. relationMatrix[i][k] = INFINITY;
  52. }
  53. }
  54.  
  55. shortestPaths = new ArrayList<>();
  56. }
  57.  
  58. public void addVertex(char lab){
  59. vertexList[countOfVertices++] = new Vertex(lab);
  60. }
  61.  
  62. public void addEdg(int start, int end, int weight){
  63. relationMatrix[start][end] = weight;
  64. }
  65.  
  66. public Integer[][] getRelationMatrix(){
  67. return relationMatrix;
  68. }
  69.  
  70. public void printRelationMatrix(){
  71. System.out.print(" ");
  72. for(int m=0; m<MAX_VERTS; m++){
  73. System.out.print(vertexList[m] + " ");
  74. }
  75. System.out.println();
  76. for(int i=0; i<MAX_VERTS; i++){
  77. System.out.print(vertexList[i] + " ");
  78. for(int j=0; j<MAX_VERTS; j++){
  79. System.out.print(relationMatrix[i][j] + " ");
  80. }
  81. System.out.println();
  82. }
  83. }
  84.  
  85. public void path(){ //выбор кратчайшего пути
  86. // задание данных для стартовой вершины
  87. int startTree = 0;
  88. vertexList[startTree].setIsInTree(true);
  89. countOfVertexInTree = 1;
  90.  
  91. //заполнение коротких путей для вершин смежных со стартовой
  92. for(int i=0; i<7; i++){
  93. int tempDist = relationMatrix[startTree][i];
  94. System.out.println("Расстояние: "+tempDist);
  95. Path path = new Path(tempDist);
  96. path.getParentVertices().add(0);
  97. shortestPaths.add(path);
  98. System.out.println("Путь: " + path);
  99.  
  100. }
  101. System.out.println("Список кратчайших путей до смежных вершин: "+ shortestPaths);
  102.  
  103. while(countOfVertexInTree < countOfVertices){
  104. int indexMin = getMin(); // получаем индекс вершины с наименьшей дистанцией еще не входящей в дерево
  105. System.out.println("indexMin=" + indexMin);
  106. int minDist = shortestPaths.get(indexMin).getDistance(); //минимальная дистанция вершин, из тех которые еще не в дереве
  107. System.out.println("minDist="+minDist);
  108.  
  109. if (minDist == INFINITY){
  110. System.out.println("В графе пристувствуют недостижимые вершины");
  111. break;
  112. }
  113. else{
  114. currentVertex = indexMin; //переводим указатель currentVert к текущей вершине
  115. System.out.println("currentVertex="+currentVertex);
  116. startToCurrent = shortestPaths.get(indexMin).getDistance(); //задаем дистанцию к текущей вершине
  117. System.out.println("startToCurrent="+startToCurrent);
  118. }
  119.  
  120. vertexList[currentVertex].setIsInTree(true); //включение текущей вершины в дерево
  121. countOfVertexInTree++; //увеличиваем счетчик вершин в дереве
  122. updateShortestPath(); //обновление списка кратчайших путей
  123.  
  124. }
  125.  
  126. System.out.println(shortestPaths);
  127.  
  128. }
  129.  
  130. private Integer getMin(){
  131. int minDist = INFINITY;
  132. int indexMin = 0;
  133.  
  134. for(int i=1; i<countOfVertices; i++){
  135. if(!vertexList[i].isInTree() && shortestPaths.get(i).getDistance() < minDist){
  136. minDist = shortestPaths.get(i).getDistance();
  137. indexMin = i;
  138. }
  139. }
  140. return indexMin;
  141. }
  142.  
  143.  
  144. public void updateShortestPath(){
  145. int vertexIndex = 1;
  146. while(vertexIndex < countOfVertices){
  147. if(vertexList[vertexIndex].isInTree()){
  148. vertexIndex++;
  149. continue;
  150. }
  151.  
  152. int currentToFringe = relationMatrix[currentVertex][vertexIndex];
  153. int startToFringe = startToCurrent + currentToFringe;
  154. int shortPathDistance = shortestPaths.get(vertexIndex).getDistance();
  155.  
  156. if(startToFringe < shortPathDistance){
  157. List<Integer> newParents = new ArrayList<>(shortestPaths.get(currentVertex).getParentVertices());
  158. newParents.add(currentVertex);
  159. shortestPaths.get(vertexIndex).setParentVertices(newParents);
  160. shortestPaths.get(vertexIndex).setDistance(startToFringe);
  161. }
  162. vertexIndex++;
  163. }
  164. }
  165.  
  166. }
  167.  
  168. class Vertex{
  169. private char label;
  170. private boolean isInTree;
  171.  
  172. public Vertex(final char label){
  173. this.label = label;
  174. this.isInTree = false;
  175. }
  176.  
  177. public char getLabel(){
  178. return this.label;
  179. }
  180.  
  181. public boolean isInTree(){
  182. return isInTree;
  183. }
  184.  
  185. public void setIsInTree(final boolean inTree){
  186. this.isInTree = inTree;
  187. }
  188.  
  189. public String toString(){
  190. return String.valueOf(label);
  191. }
  192.  
  193. }
  194.  
  195. class Path{
  196. private int distance;
  197. private List<Integer> parentVertices;
  198.  
  199. public Path(int distance){
  200. this.distance = distance;
  201. this.parentVertices = new ArrayList<>();
  202. }
  203.  
  204. public int getDistance(){
  205. return distance;
  206. }
  207.  
  208. public void setDistance(int distance){
  209. this.distance = distance;
  210. }
  211.  
  212. public List<Integer> getParentVertices(){
  213. return parentVertices;
  214. }
  215.  
  216. public void setParentVertices(List<Integer> parentVertices){
  217. this.parentVertices = parentVertices;
  218. }
  219.  
  220. public String toString(){
  221. return "{Родительская вершина: "+parentVertices + "; "+ "расстояние:" + distance + "}";
  222. }
  223. }
Success #stdin #stdout 0.2s 59856KB
stdin
Standard input is empty
stdout
Расстояние: 100000000
Путь: {Родительская вершина: [0]; расстояние:100000000}
Расстояние: 3
Путь: {Родительская вершина: [0]; расстояние:3}
Расстояние: 5
Путь: {Родительская вершина: [0]; расстояние:5}
Расстояние: 7
Путь: {Родительская вершина: [0]; расстояние:7}
Расстояние: 100000000
Путь: {Родительская вершина: [0]; расстояние:100000000}
Расстояние: 100000000
Путь: {Родительская вершина: [0]; расстояние:100000000}
Расстояние: 100000000
Путь: {Родительская вершина: [0]; расстояние:100000000}
Список кратчайших путей до смежных вершин: [{Родительская вершина: [0]; расстояние:100000000}, {Родительская вершина: [0]; расстояние:3}, {Родительская вершина: [0]; расстояние:5}, {Родительская вершина: [0]; расстояние:7}, {Родительская вершина: [0]; расстояние:100000000}, {Родительская вершина: [0]; расстояние:100000000}, {Родительская вершина: [0]; расстояние:100000000}]
indexMin=1
minDist=3
currentVertex=1
startToCurrent=3
indexMin=2
minDist=5
currentVertex=2
startToCurrent=5
indexMin=3
minDist=7
currentVertex=3
startToCurrent=7
indexMin=4
minDist=9
currentVertex=4
startToCurrent=9
indexMin=5
minDist=10
currentVertex=5
startToCurrent=10
indexMin=6
minDist=14
currentVertex=6
startToCurrent=14
[{Родительская вершина: [0]; расстояние:100000000}, {Родительская вершина: [0]; расстояние:3}, {Родительская вершина: [0]; расстояние:5}, {Родительская вершина: [0]; расстояние:7}, {Родительская вершина: [0, 1]; расстояние:9}, {Родительская вершина: [0, 3]; расстояние:10}, {Родительская вершина: [0, 3, 5]; расстояние:14}]