-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestPath.java
More file actions
62 lines (55 loc) · 1.7 KB
/
ShortestPath.java
File metadata and controls
62 lines (55 loc) · 1.7 KB
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
package datastructure.graph;
import java.util.LinkedList;
import java.util.Queue;
/**
* The type Shortest path.
*/
public class ShortestPath {
/**
* Gets shortest path.
*
* @param graph the graph
* @param source the source
* @param destination the destination
* @return the shortest path
*/
public static int getShortestPath(AdjacencyListGraph graph, int source, int destination) {
int distance = 0;
if (source == destination)
return distance;
int vertices = graph.vertices;
boolean[] visited = new boolean[vertices];
int[] distanceArray = new int[vertices];
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
while (!queue.isEmpty()) {
int currentNode = queue.remove();
LinkedList<Integer> temp = null;
if (graph.adjacencyList[currentNode] != null)
temp = graph.adjacencyList[currentNode];
for (int i = 0; i < temp.size(); i++) {
if (!visited[temp.get(i)]) {
queue.add(temp.get(i));
distanceArray[temp.get(i)] = distanceArray[currentNode] + 1;
}
if (temp.get(i) == destination)
return distanceArray[temp.get(i)];
}
}
return distance;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[]) {
AdjacencyListGraph g = new AdjacencyListGraph(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(3, 4);
g.addEdge(1, 4);
System.out.println(getShortestPath(g, 0, 4));
}
}