Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package dijstras;
- import java.util.Scanner;
- /**
- *
- * @author manth
- */
- public class Dijstras {
- /**
- * @param args the command line arguments
- */
- static double graph[][];
- public static void main(String[] args) {
- build_graph();
- shortest_path();
- }
- public static void shortest_path()
- {
- int selected[]=new int[graph.length];
- double distance[]=new double[graph.length];
- for(int i=0;i<graph.length;i++)
- {
- distance[i]=Double.POSITIVE_INFINITY;
- }
- int current=0;
- distance[current]=0;
- selected[current]=1;
- int preced[]=new int[graph.length];
- int k=0;
- while(!all_selected(selected))
- {
- double smalldist=Double.POSITIVE_INFINITY;
- for(int i=0;i<graph.length;i++)
- {
- double new_dist=distance[current]+graph[current][i];
- if(selected[i]==0)
- {
- if(new_dist<distance[i])
- {
- distance[i]=new_dist;
- preced[i]=current+1;
- }
- if(smalldist>distance[i])
- {
- k=i;
- smalldist=distance[i];
- }
- }
- }
- current=k;
- selected[current]=1;
- }
- for(double d:distance)
- {
- System.out.println(d);
- }
- System.out.println("preced array ");
- for(double d:preced)
- {
- System.out.println(d);
- }
- }
- public static Boolean all_selected(int []selected)
- {
- for(int i=0;i<selected.length;i++)
- {
- if(selected[i]==0)
- return false;
- }
- return true;
- }
- public static void build_graph()
- {
- Scanner sc=new Scanner(System.in);
- System.out.println(" Enter Number nodes ");
- int no_nodes=Integer.parseInt(sc.nextLine());
- System.out.println(" Enter Number of edges ");
- int no_edges=Integer.parseInt(sc.nextLine());
- graph=new double[no_nodes][no_nodes];
- for(int i=0;i<no_nodes;i++)
- {
- for(int j=0;j<no_nodes;j++)
- {
- graph[i][j]=Double.POSITIVE_INFINITY;
- }
- }
- for(int i=0;i<no_edges;i++)
- {
- String input[]=sc.nextLine().split(" ");
- int from_node=Integer.parseInt(input[0])-1;
- int to_node=Integer.parseInt(input[1])-1;
- double cost=Double.parseDouble(input[2]);
- graph[from_node][to_node]=cost;
- graph[to_node][from_node]=cost;
- }
- for(int i=0;i<no_nodes;i++)
- {
- for(int j=0;j<no_nodes;j++)
- {
- System.out.print(graph[i][j]+" ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement