Dijkstra's algorithm in java
package dijkstra;
import java.util.Scanner;
public class Demo {
int no_nodes;
int matrix[][];
int s; // source
int d[];// distance
int p[]; // parent
boolean visited[]; // to track visited node
Scanner in=new Scanner(System.in);
public void input(){
System.out.println("Enter no. of Nodes");
no_nodes=in.nextInt();
matrix=new int[no_nodes][no_nodes];
d=new int[no_nodes];
p=new int[no_nodes];
visited=new boolean[no_nodes];
System.out.println("Enter connection matrix");
System.out.print(" ");
for(int i=0;i<no_nodes;i++){
char ch=(char)(65+i);
System.out.print(ch+"\t");
}
System.out.println();
for(int i=0;i<no_nodes;i++){
System.out.print((char)(65+i));
for(int j=0;j<no_nodes;j++){
matrix[i][j]=in.nextInt();
}
System.out.println();
}
}
public void initialize(){
for(int i=0;i<no_nodes;i++){
d[i]=1000; // infinity
p[i]=-1 ;// nil for parents
visited[i]=false;
}
d[s]=0;
}
public int findVertex(){
int min=1000;
int vertex=0;
for(int i=0;i<no_nodes;i++){
if(visited[i]==false && d[i]<min){
min=d[i];
vertex=i;
}
visited[vertex]=true;
}
return vertex;
}
public void algorithm(){
System.out.println("Enter source");
s=in.nextInt();
initialize();
int c=no_nodes;
while(c>0){
// find vertex to go
int vertex=findVertex();
c--;
for(int i=0; i<no_nodes;i++){
if(matrix[vertex][i]>0){
// relax
int dis=matrix[vertex][i];
if(dis+d[vertex]<d[i]){
d[i]=dis+d[vertex];
p[i]=vertex;
}
}
}
}
System.out.println("Source= "+(char)(65+s));
System.out.println();
System.out.print(" ");
System.out.print("\tD"+"\tP\n");
for(int i=0;i<no_nodes;i++){
System.out.print((char)(65+i)+"\t");
System.out.print(d[i]+"\t");
System.out.print((char)(65+p[i])+"\n");
}
}
public static void main(String args[]){
Demo obj=new Demo();
obj.input();
obj.algorithm();
}
}
0 comments:
Post a Comment