-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC.java
More file actions
93 lines (74 loc) · 2.49 KB
/
Copy pathC.java
File metadata and controls
93 lines (74 loc) · 2.49 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
import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) throws IOException{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
PrintWriter out= new PrintWriter(System.out);
StringTokenizer st1= new StringTokenizer(br.readLine(), " ");
int nodes= Integer.parseInt(st1.nextToken());
int edges= Integer.parseInt(st1.nextToken());
int s= Integer.parseInt(st1.nextToken());
int d= Integer.parseInt(st1.nextToken());
//Make arrayList before making the graph
ArrayList<Integer>[] graph = new ArrayList[nodes+1];
for(int i=1; i<= nodes; i++){
graph[i]= new ArrayList<>();
}
//making the graph
if(edges>0){
StringTokenizer st_u= new StringTokenizer(br.readLine(), " ");
StringTokenizer st_v= new StringTokenizer(br.readLine(), " ");
for(int i=0; i<edges; i++){
int u= Integer.parseInt(st_u.nextToken());
int v= Integer.parseInt(st_v.nextToken());
graph[u].add(v);
graph[v].add(u);
}
}
//lexicographically
for(int i=1; i<=nodes; i++){
Collections.sort(graph[i]);
}
//Bfs
boolean[] visited= new boolean[nodes+1];
int[] parent= new int[nodes+1];
int[] distance= new int[nodes+1];
Queue<Integer> q=new LinkedList<>();
q.add(s);
visited[s]= true;
distance[s]=0;
parent[s]=0;
while(!q.isEmpty()){
int node= q.poll();
for(int neighbor: graph[node]){
if(!visited[neighbor]){
q.add(neighbor);
visited[neighbor]= true;
distance[neighbor]=distance[node]+1;
parent[neighbor]= node;
}
}
}
//couldn't reach
if(!visited[d]){
out.println(-1);
out.flush();
return;
}
//If reaches, backtrack
ArrayList<Integer> path= new ArrayList<>();
int curr= d;
while(curr!=0){ //stops when parent becomes 0
path.add(curr);
curr= parent[curr];
}
//reverse the path
Collections.reverse(path);
out.println(distance[d]); //distance
for(int i=0; i<path.size(); i++){
out.print(path.get(i));
if(i+1<path.size()) out.print(" ");
}
out.flush();
}
}