-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dominos.java
77 lines (68 loc) · 2.07 KB
/
Dominos.java
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
import java.util.ArrayList;
import java.util.*;
public class Dominos {
public static void main(String[] args) {
Kattio sc = new Kattio(System.in, System.out);
int testCase = sc.getInt();
for (int i = 0; i < testCase; i++) {
Graph g = new Graph(sc.getInt());
int limit = sc.getInt();
for (int j = 0; j < limit; j++) {
int a = sc.getInt();
int b = sc.getInt();
g.addEdge(a - 1, b - 1);
}
sc.println(g.printSCCs());
}
sc.close();
}
}
// This class represents a directed graph using adjacency list
// representation
class Graph {
private int v; // No. of vertices
private ArrayList<Integer>[] adj; // Adjacency List
Graph(int v) {
this.v = v;
@SuppressWarnings("unchecked")
ArrayList<Integer>[] adjacency = (ArrayList<Integer>[]) new ArrayList<?>[v];
adj = adjacency;
for (int i = 0; i < v; ++i)
adj[i] = new ArrayList<>();
}
void addEdge(int v, int w) {
adj[v].add(w);
}
Stack<Integer> toposort(ArrayList<Integer>[] arr) {
Stack<Integer> stack = new Stack<>();
boolean[] visited = new boolean[arr.length];
for (int i = 0; i < arr.length; i++) {
if (!visited[i]) {
DFSrec(i, visited, arr, stack);
}
}
return stack;
}
void DFSrec(int u, boolean visited[], ArrayList<Integer>[] adj, Stack<Integer> stack) {
visited[u] = true;
for (Integer vtx : adj[u]) {
if (!visited[vtx]) {
DFSrec(vtx, visited, adj, stack);
}
}
stack.push(u);
}
int printSCCs() {
Stack<Integer> stack = toposort(adj);
boolean[] visited = new boolean[v];
int result = 0;
while (!stack.isEmpty()) {
int u = stack.pop();
if (!visited[u]) {
result++;
DFSrec(u, visited, adj, new Stack<Integer>());
}
}
return result;
}
}