Dijkstra’s shortest path algorithm in java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | // dijsktra algorithm import java.util.*; public class dijsktra { public static void main(String[] args) { int weight; Scanner vinnu = new Scanner(System.in); Queue<node> queue = new LinkedList<node>(); System.out.println("Enter the length of the array "); int n = vinnu.nextInt(); int graph[][] = new int[n][n]; int distance[] = new int[n]; System.out.println("Enter the elements of the array "); for (int i = 0; i < n; i++) { distance[i] = Integer.MAX_VALUE; for (int j = 0; j < n; j++) { graph[i][j] = vinnu.nextInt(); } } distance[0]=0; queue.add(new node(0, 0)); //initial node will be at distance 0 and add it to the queue while (!queue.isEmpty()) { // run while loop until there is no node in the queue node u = queue.poll(); for (int i = 0; i < n; i++) { //for all node in the adjacent of current node weight = graph[u.number][i]; if ((weight > 0) && (u.distance + weight) < (distance[i])) { distance[i] = u.distance + weight; int dis = distance[i]; queue.add(new node(i, dis)); // add the queue // System.out.println("now added - " + i + " ----" + distance[i]); } } } System.out.println(" distances = "); for (int j = 0; j < n; j++) { System.out.println(j + " ------ " + distance[j]); } } } class node { int number; int distance; node(int number, int distance) { this.number = number; this.distance = distance; } } |
Dijkstra’s shortest path algorithm in java
Reviewed by Unknown
on
10:07
Rating:
No comments: