Dijkstra for All Pair Shortest Path using Java
January 9th, 2009 | by admin |Graph Problem Using Java.
Mostly, people used Floyd-Warshall to solve All Pair Shortest Path problem. But, I try to solve all pair shortest path problem using Dijkstra and it works.
The Source code can be seen below.
import java.util.*;
public class DijkstraASP{
public static void main(String args[]){
Main m =new Main();
}
}
class Verteks{
int no;
int value;
String color;
Verteks(int no , int value){
this.no = no;
this.value = value;
}
Verteks(int no,String color){
this.no = no;
this.color = color;
}
public String getColor(){
return color;
}
public void setColor(String color){
this.color = color;
}
public int getValue(){
return value;
}
public int getNo(){
return no;
}
public void setValue(int a){
value = a;
}
}
class Main{
public Main(){
int n=2;
Scanner in = new Scanner(System.in);
PriorityQueue<Verteks> pq = new PriorityQueue<Verteks>
(n,new Comparator<Verteks>(){
public int compare(Verteks a,Verteks b){
if(a.getValue() < b.getValue())
return -1;
else
return 1;
}
});
Verteks d[][] = new Verteks[n][n];
int edge[][] = new int[n][n];
for(int i=0 ; i< n ; i++){
Arrays.fill(edge[i] , 0);
for(int j=0 ; j< n ; j++){
d[i][j]=new Verteks(j,Integer.MAX_VALUE);
}
}
for(int i=0 ; i< n ; i++){
d[i][i].setValue(0);
}
edge[0][1] =edge[1][0]=2;
edge[1][2]=edge[2][1]=1;
edge[0][2]= edge[2][0]=4;
int u=0;
for(int i=0 ; i< n ; i++){
pq.add(d[i][i]);
while(!pq.isEmpty()){
u = pq.poll().no;
for(int j=0 ; j< n ; j++){
if(edge[i][j]!=0){
if((d[i][j].getValue()) >
(d[i][u].value+edge[u][j])){
d[i][j].setValue(
d[i][u].value+edge[u][j]);
pq.add(d[i][j]);
}
}
}
}
}
for(int i=0 ; i< n ; i++){
for(int j=0 ; j< n ; j++){
System.out.println(d[i][j].getValue());
}
}
}
}
5 Responses to “Dijkstra for All Pair Shortest Path using Java”
By utinkisinuevy on Feb 24, 2009 | Reply
Thank you!
By Ratozemaneona on Mar 2, 2009 | Reply
Thank you!
By ami on Mar 14, 2009 | Reply
Blognya dolot isinya banyak ‘gituan’. mantab gan
hehe :p
blogwalking neeh
By admin on Mar 17, 2009 | Reply
you’re welcome. .
@ami
orang bule gak ngerti tuh mi baca postingan lo.XD
dokumentasi mi, hehehe
By yogie on Jun 10, 2009 | Reply
mas mau tanya kalo dijktra tu sama dengan jalur terpendek(shortest path)gak?klo mmg sama ada referensi utk dibahasa avenue(arview gis) gak mas?makasi before…GBU