-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColorfulGraph.java
66 lines (60 loc) · 1.56 KB
/
ColorfulGraph.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
/** #dfs #graph #todo #dsu */
import java.util.ArrayList;
import java.util.Scanner;
public class ColorfulGraph {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<ArrayList<Node>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
graph.get(a - 1).add(new Node(b - 1, c - 1));
graph.get(b - 1).add(new Node(a - 1, c - 1));
}
// query
int q = sc.nextInt();
for (int k = 0; k < q; k++) {
int res = 0;
int u = sc.nextInt();
int v = sc.nextInt();
// interate each color
for (int i = 0; i < m; ++i) {
boolean[] visited = new boolean[101];
if (dfs(u - 1, i, v - 1, visited, graph)) {
++res;
}
}
System.out.println(res);
}
}
private static boolean dfs(
int v, int col, int dst, boolean[] visited, ArrayList<ArrayList<Node>> graph) {
visited[v] = true;
if (v == dst) {
return true;
}
for (int i = 0; i < graph.get(v).size(); i++) {
Node neighbour = graph.get(v).get(i);
if (neighbour.color == col && !visited[neighbour.idx]) {
if (dfs(neighbour.idx, col, dst, visited, graph)) {
return true;
}
}
}
return false;
}
}
class Node {
int idx;
int color;
Node(int idx, int color) {
this.idx = idx;
this.color = color;
}
}