public class ShortTree {
private static final int infinity=65535;
private String [] topPoint={"0","1","2","3","4","5","6","7","8"};
private int length=9;
private int[][] sides={
{0, 1, 5, infinity, infinity, infinity, infinity, infinity,infinity},
{1,0, 3,7, 5, infinity, infinity,infinity,infinity},
{5, 3, 0, infinity,1, 7, infinity, infinity,infinity},
{infinity, 7, infinity,0, 2,infinity, 3, infinity,infinity},
{infinity, 5, 1, 2,0, 3,6, 9,infinity},
{infinity,infinity, 7, infinity, 3,0, infinity,5,infinity},
{infinity, infinity,infinity, 3, 6, infinity,0, 2,7},
{infinity, infinity, infinity, infinity,9, 5, 2,0,4},
{infinity, infinity,infinity, infinity,infinity, infinity, 7, 4,0}
};
public static void main(String[] args) {
ShortTree st=new ShortTree();
st.dijkstra(0);
}
private void dijkstra(int v0){
int []patharc=new int[9];
int []shortPathTable=new int[9];
int min;
int k=v0;
int finali[]=new int[9];
for (int v = 0; v < length; v++) {
finali[v]=0;
patharc[v]=0;
shortPathTable[v]=sides[v0][v];
}
shortPathTable[v0]=0;
finali[k]=1;
for (int v = 0; v < length; v++) {
min=infinity;
for (int w = 0; w < length; w++) {
if(finali[w]==0 && shortPathTable[w]<min){
k=w;
min=shortPathTable[w];
}
}
finali[k]=1;
for (int w = 0; w < length; w++) {
if(finali[w]==0 && (min+sides[k][w])<shortPathTable[w]){
shortPathTable[w]=min+sides[k][w];
patharc[w]=k;
}
}
}
System.out.println(patharc);
}
}
private void floyd(){
int p[][]={
{0, 1, 2, 3, 4, 5, 6, 7,8},
{0, 1, 2, 3, 4, 5, 6, 7,8},
{0, 1, 2, 3, 4, 5, 6, 7,8},
{0, 1, 2, 3, 4, 5, 6, 7,8},
{0, 1, 2, 3, 4, 5, 6, 7,8},
{0, 1, 2, 3, 4, 5, 6, 7,8},
{0, 1, 2, 3, 4, 5, 6, 7,8},
{0, 1, 2, 3, 4, 5, 6, 7,8},
{0, 1, 2, 3, 4, 5, 6, 7,8}
};
int d[][]=sides;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length; j++) {
for (int k = 0; k < length; k++) {
if(d[j][k] > d[j][i]+d[i][k] ){
d[j][k]=d[j][i]+d[i][k];
p[j][k]=p[j][i];
}
}
}
}
System.out.println(p);
}