-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestPathInUndirectedGraph.java
More file actions
56 lines (55 loc) · 1.47 KB
/
ShortestPathInUndirectedGraph.java
File metadata and controls
56 lines (55 loc) · 1.47 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
import java.util.*;
public class ShortestPath{
static void distanceArray(int i,ArrayList<ArrayList<Integer>> graph,int e)
{
int dis[] = new int[i];
for(int j=0;j<i;j++)
{
dis[j]=100000000;
}
int k=0;
dis[k]=0;
Queue<Integer> q = new LinkedList<Integer>();
q.add(k);
while(!q.isEmpty())
{
int n = q.poll();
for(int x:graph.get(n))
{
if(dis[n]+1<dis[x])
{
dis[x]=dis[n]+1;
q.add(x);
}
}
}
System.out.print("shortest path is: ");
for(int j=0;j<i;j++)
{
System.out.print(dis[j]+" ");
}
}
public static void main(String arg[])
{
ArrayList<ArrayList<Integer>> graph;
Scanner sc = new Scanner(System.in);
System.out.println("number of nodes");
int node = sc.nextInt();
System.out.println("number of edges");
int e = sc.nextInt();
graph = new ArrayList<ArrayList<Integer>>(node);
for(int i=0;i<node;i++)
{
graph.add(new ArrayList<Integer>());
}
System.out.println("enter v and u");
for(int i=0;i<e;i++)
{
int v = sc.nextInt();
int u = sc.nextInt();
graph.get(v).add(u);
graph.get(u).add(v);
}
distanceArray(node,graph,e);
}
}