-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathshortestPath.java
More file actions
61 lines (48 loc) · 1.22 KB
/
shortestPath.java
File metadata and controls
61 lines (48 loc) · 1.22 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
import java.io.*;
import java.util.*;
public class shortestPath{
public static void addEdge(ArrayList<ArrayList<Integer>> adj,int v, int u){
adj.get(u).add(v);
adj.get(v).add(u);
}
static void sPath(ArrayList<ArrayList<Integer>> adj,int v, int s, boolean[] visited, int[] sDistance){
Queue<Integer> q = new LinkedList<>();
q.add(s);
sDistance[s]=0;
visited[s]=true;
while(q.isEmpty()==false){
int x=q.poll();
for(int u:adj.get(x)){
if(visited[u]==false){
sDistance[u]=sDistance[x]+1;
visited[u]=true;
q.add(u);
}
}
}
for(int i=0;i<v;i++){
System.out.print(sDistance[i]+" ");
}
}
static void path(ArrayList<ArrayList<Integer>> adj,int v, int s){
boolean[] visited = new boolean[v];
int[] distance = new int[v];
Arrays.fill(distance,Integer.MAX_VALUE);
sPath(adj,v,s,visited,distance);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i,v,s;
v=4;
s=0;
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
for(i=0;i<v;i++)
adj.add(new ArrayList<Integer>());
addEdge(adj,0,1);
addEdge(adj,1,2);
addEdge(adj,2,3);
addEdge(adj,0,2);
addEdge(adj,1,3);
path(adj,v,s);
}
}