The 'p' is the number of nodes. So now in my solution the user has to type in all the matrix elements, in case of 7 nodes, 49 numbers. I don't want it this way. I would like to ask the user the distances from one point to the other. Sorry for the weird names in my program, they're in my language. latogatott = visited, tav=distance
package legrovidebb_ut;
import java.util.Scanner;
public class Legrovidebb_ut {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Adja meg a pontok szamat: ");
int p;
p = scan.nextInt( );
int[][] matrix = new int [p][p];
int[] tav = new int[p];
int[] latogatott = new int[p];
int[] pre = new int[p];
int min;
int nextNode = 0;
System.out.println("Enter the matrix!");
for (int i=0; i<p; i++){
latogatott[i]=0;
pre[i]=0;
for (int j=0;j<p;j++){
matrix[i][j] = scan.nextInt();
if(matrix[i][j]== 0)
matrix[i][j]=999;
}
}
tav = matrix[0];
tav[0]=0;
latogatott[0]=1;
for (int i=0;i<p;i++){
min=999;
for(int j=0;j<p;j++){
if(min>tav[j] && latogatott[j]!=1){
min=tav[j];
nextNode=j;
}
}
latogatott[nextNode]=1;
for(int c=0;c<p;c++){
if(latogatott[c]!=1){
if(min+matrix[nextNode][c]<tav[c]){
tav[c]=min+matrix[nextNode][c];
pre[c]=nextNode;
}
}
}
}
for (int i=0;i<p;i++){
System.out.print("|" + tav[i]);
}
System.out.println("|");
for(int i=0;i<p;i++){
int j;
System.out.print("Ut: " + (i+1));
j=i;
do{
j=pre[j];
System.out.println(" <- " + (j+1));
}while(j!=0);
System.out.println();
}
}
}
If your graph is undirected and you want the user to input the distances between each two nodes (as stated in your comment), you will need a loop through all your nodes and another loop through all the other nodes, as a distance for 2-1 is not needed if you have a distance for 1-2: