import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static void main
(String[] args
) { Graph graph = new Graph();
graph.addVertex('A'); // 0
graph.addVertex('B'); // 1
graph.addVertex('C'); // 2
graph.addVertex('D'); // 3
graph.addVertex('E'); // 4
graph.addVertex('F'); // 5
graph.addVertex('G'); // 6
graph.addEdg(0, 1, 3);
graph.addEdg(0, 2, 5);
graph.addEdg(0, 3, 7);
graph.addEdg(1, 4, 6);
graph.addEdg(2, 4, 4);
graph.addEdg(2, 3, 3);
graph.addEdg(3, 5, 3);
graph.addEdg(4, 6, 6);
graph.addEdg(5, 6, 4);
//graph.printRelationMatrix();
graph.path();
}
}
class Graph{
private final int MAX_VERTS = 7;
private final int INFINITY = 100000000;
private Vertex vertexList[];
private Integer relationMatrix
[][]; private int countOfVertices;
private int countOfVertexInTree;
private List<Path> shortestPaths; //список данных кратчайших путей
private int currentVertex;
private int startToCurrent; //расстояние до currentVertex
public Graph(){
vertexList = new Vertex[MAX_VERTS];
relationMatrix
= new Integer[MAX_VERTS
][MAX_VERTS
]; countOfVertices = 0;
countOfVertexInTree = 0;
for(int i=0; i<MAX_VERTS; i++){
for(int k=0; k<MAX_VERTS; k++){
relationMatrix[i][k] = INFINITY;
}
}
shortestPaths = new ArrayList<>();
}
public void addVertex(char lab){
vertexList[countOfVertices++] = new Vertex(lab);
}
public void addEdg(int start, int end, int weight){
relationMatrix[start][end] = weight;
}
public Integer[][] getRelationMatrix
(){ return relationMatrix;
}
public void printRelationMatrix(){
for(int m=0; m<MAX_VERTS; m++){
System.
out.
print(vertexList
[m
] + " "); }
for(int i=0; i<MAX_VERTS; i++){
System.
out.
print(vertexList
[i
] + " "); for(int j=0; j<MAX_VERTS; j++){
System.
out.
print(relationMatrix
[i
][j
] + " "); }
}
}
public void path(){ //выбор кратчайшего пути
// задание данных для стартовой вершины
int startTree = 0;
vertexList[startTree].setIsInTree(true);
countOfVertexInTree = 1;
//заполнение коротких путей для вершин смежных со стартовой
for(int i=0; i<7; i++){
int tempDist = relationMatrix[startTree][i];
System.
out.
println("Расстояние: "+tempDist
); Path path = new Path(tempDist);
path.getParentVertices().add(0);
shortestPaths.add(path);
System.
out.
println("Путь: " + path
);
}
System.
out.
println("Список кратчайших путей до смежных вершин: "+ shortestPaths
);
while(countOfVertexInTree < countOfVertices){
int indexMin = getMin(); // получаем индекс вершины с наименьшей дистанцией еще не входящей в дерево
System.
out.
println("indexMin=" + indexMin
); int minDist = shortestPaths.get(indexMin).getDistance(); //минимальная дистанция вершин, из тех которые еще не в дереве
System.
out.
println("minDist="+minDist
);
if (minDist == INFINITY){
System.
out.
println("В графе пристувствуют недостижимые вершины"); break;
}
else{
currentVertex = indexMin; //переводим указатель currentVert к текущей вершине
System.
out.
println("currentVertex="+currentVertex
); startToCurrent = shortestPaths.get(indexMin).getDistance(); //задаем дистанцию к текущей вершине
System.
out.
println("startToCurrent="+startToCurrent
); }
vertexList[currentVertex].setIsInTree(true); //включение текущей вершины в дерево
countOfVertexInTree++; //увеличиваем счетчик вершин в дереве
updateShortestPath(); //обновление списка кратчайших путей
}
System.
out.
println(shortestPaths
);
}
int minDist = INFINITY;
int indexMin = 0;
for(int i=1; i<countOfVertices; i++){
if(!vertexList[i].isInTree() && shortestPaths.get(i).getDistance() < minDist){
minDist = shortestPaths.get(i).getDistance();
indexMin = i;
}
}
return indexMin;
}
public void updateShortestPath(){
int vertexIndex = 1;
while(vertexIndex < countOfVertices){
if(vertexList[vertexIndex].isInTree()){
vertexIndex++;
continue;
}
int currentToFringe = relationMatrix[currentVertex][vertexIndex];
int startToFringe = startToCurrent + currentToFringe;
int shortPathDistance = shortestPaths.get(vertexIndex).getDistance();
if(startToFringe < shortPathDistance){
List<Integer> newParents = new ArrayList<>(shortestPaths.get(currentVertex).getParentVertices());
newParents.add(currentVertex);
shortestPaths.get(vertexIndex).setParentVertices(newParents);
shortestPaths.get(vertexIndex).setDistance(startToFringe);
}
vertexIndex++;
}
}
}
class Vertex{
private char label;
private boolean isInTree;
public Vertex(final char label){
this.label = label;
this.isInTree = false;
}
public char getLabel(){
return this.label;
}
public boolean isInTree(){
return isInTree;
}
public void setIsInTree(final boolean inTree){
this.isInTree = inTree;
}
}
}
class Path{
private int distance;
private List<Integer> parentVertices;
public Path(int distance){
this.distance = distance;
this.parentVertices = new ArrayList<>();
}
public int getDistance(){
return distance;
}
public void setDistance(int distance){
this.distance = distance;
}
public List<Integer> getParentVertices(){
return parentVertices;
}
public void setParentVertices(List<Integer> parentVertices){
this.parentVertices = parentVertices;
}
return "{Родительская вершина: "+parentVertices + "; "+ "расстояние:" + distance + "}";
}
}