Repository navigation
Expand file tree
/
Copy pathShortest Path Print.java
More file actions
94 lines (80 loc) · 2.02 KB
/
Copy pathShortest Path Print.java
File metadata and controls
94 lines (80 loc) · 2.02 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.*;
class Graph{
int nodeCount;
ArrayList<Integer>[] g;
boolean[] vis;
int[] par;
public Graph(int nodes){
this.nodeCount=nodes+1;
g=new ArrayList[nodeCount];
vis=new boolean[nodeCount];
par=new int[nodeCount];
for(int i=0;i<nodeCount;i++){
g[i]=new ArrayList<>();
par[i]=-1;
}
}
public void addEdge(int a, int b){
g[a].add(b);
g[b].add(a);
}
public void DFS(int node){
if(vis[node]) return;
vis[node]=true;
System.out.println("visiting "+node);
for(int child:g[node]){
DFS(child);
}
}
public void BFS(int root){
Queue<Integer> q=new ArrayDeque<>();
q.add(root);
vis[root]=true;
while(!q.isEmpty()){
int node=q.poll();
for(int child:g[node]){
if(vis[child]) continue;
par[child]=node;
q.add(child);
vis[child]=true;
}
}
}
boolean isVisited(int node){
return vis[node];
}
public void PrintPath(int dest){
ArrayList<Integer> path=new ArrayList<>();
int curr=dest;
while(par[curr]!=-1){
path.add(curr);
curr=par[curr];
}
path.add(1);
int n=path.size();
System.out.println(n);
for(int i=n-1;i>=0;i--){
System.out.print(path.get(i)+" ");
}
}
}
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
Graph graph=new Graph(n);
for(int i=0;i<m;i++){
int a=sc.nextInt();
int b=sc.nextInt();
graph.addEdge(a, b);
}
graph.BFS(1);
if(graph.isVisited(n)){
graph.PrintPath(n);
}else{
System.out.println("IMPOSSIBLE");
}
sc.close();
}
}