- //dijksh
- import java.util.*;
- class graph
- {
- int g[][],d[],visited[],p[];
- int v,e;
- void creategraph()
- {
- int a,b,w;
- Scanner kbd=new Scanner(System.in);
- System.out.println("enter nio v");
- v=kbd.nextInt();
- System.out.println("enterno e");
- e=kbd.nextInt();
- g=new int[v+1][v+1];
- for (int i=1;i<=v;i++)
- for (int j=1;j<=v;j++)
- g[i][j]=0;
- for(int i=1;i<=e;i++)
- {
- System.out.println("enter edge info");
- a=kbd.nextInt();b=kbd.nextInt();
- System.out.println("enter edge wt");
- w=kbd.nextInt();
- g[a][b]=g[a][b]=w;
- }
- }
- void calldij()
- {
- visited=new int[v+1];
- d=new int[v+1];
- p=new int[v+1];
- for (int i=1;i<=v;i++)
- p[i]=visited[i]=0;
- for (int i=1;i<=v;i++)
- d[i]=32767;
- dij();
- }
- void dij()
- {
- int current,c,source,dest,mincost=0;
- System.out.println("enter souce n destination");
- Scanner kbd=new Scanner(System.in);
- source=kbd.nextInt();
- dest=kbd.nextInt();
- current=source;
- visited[current]=1;
- d[current]=0;
- while(current!=dest)
- {
- int dc=d[current];
- for(int i=1;i<=v;i++)
- {
- if(g[current][i]!=0&&visited[i]!=1)
- if(g[current][i]+dc<d[i])
- {
- d[i]=g[current][i]+dc;
- p[i]=current;
- }
- }
- int min=32767;
- for(int i=1;i<=v;i++)
- {
- if(visited[i]!=1&&d[i]<min)
- {
- min=d[i];
- current=i;
- }
- }
- visited[current]=1;
- }
- System.out.println("shortest dist"+d[dest]);
- }
- }
- public class dj
- {
- public static void main(String args[])
- {
- graph g=new graph();
- g.creategraph();
- g.calldij();
- }
- }
1551 characters | 114 lines | 1.51 KB
