-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestFightRoute.java
More file actions
80 lines (61 loc) · 2.1 KB
/
LongestFightRoute.java
File metadata and controls
80 lines (61 loc) · 2.1 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
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class LongestFightRoute {
ArrayList<ArrayList<Integer>> adj;
public LongestFightRoute(int n){
adj = new ArrayList<>();
for(int i = 0; i <= n; i++){
adj.add(new ArrayList<>());
}
}
public void addEdge(int src ,int dest){
adj.get(src).add(dest);
}
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
public void dfs(int node , ArrayList<ArrayList<Integer>> adj , boolean vis[],int end){
vis[node] = true;
temp.add(node);
if(node == end){
ans.add(new ArrayList<>(temp));
}else{
for(int it : adj.get(node)){
if(!vis[it]){
dfs(it, adj, vis, end);
}
}
}
temp.remove(temp.size() - 1);
vis[node] = false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
LongestFightRoute l = new LongestFightRoute(n);
for(int i = 0; i < m; i++){
int src = sc.nextInt();
int dest = sc.nextInt();
l.addEdge(src , dest );
}
boolean[] vis = new boolean[n + 1];
int start = 1;
int end = n;
l.dfs(start, l.adj, vis, end);
Collections.sort(l.ans, (list1, list2) -> {
int len = Math.min(list1.size(), list2.size());
for (int i = 0; i < len; i++) {
if (!list1.get(i).equals(list2.get(i))) {
return list1.get(i) - list2.get(i);
}
}
return list1.size() - list2.size(); // Sort by length if all elements so far are equal
});
System.out.println(l.ans.get(l.ans.size() - 1).size());
for (int it : l.ans.get(l.ans.size() - 1)) {
System.out.print(it + " ");
}
System.out.println();
}
}