-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShortestPathUDBFS.java
47 lines (37 loc) · 1.25 KB
/
ShortestPathUDBFS.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
package Graphs;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class ShortestPathUDBFS {
public static int calculateDistance(int source, int destination, ArrayList<ArrayList<Integer>> adjList){
int[] dist = new int[adjList.size() + 1];
Arrays.fill(dist, Integer.MAX_VALUE);
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
dist[source] = 0;
while (!queue.isEmpty()){
int node = queue.poll();
for (int v: adjList.get(node)){
int distance = dist[v];
if(distance > dist[node] + 1) {
dist[v] = dist[node] + 1;
queue.add(v);
}
}
}
return dist[destination];
}
public static void main(String[] args){
Graph graph = new Graph(12);
graph.addEdge(0 , 1);
graph.addEdge(1, 2);
graph.addEdge(2,6);
graph.addEdge(0,3);
graph.addEdge(3,4);
graph.addEdge(4,5);
graph.addEdge(5,6);
ArrayList<ArrayList<Integer>> adjList = Graph.getAdj();
System.out.println("Shortest Distance: " + calculateDistance(0, 6, adjList));
}
}