|
11 | 11 | import java.util.Map;
|
12 | 12 | import java.util.PriorityQueue;
|
13 | 13 | import java.util.Queue;
|
| 14 | +import java.util.Set; |
14 | 15 | import java.util.TreeMap;
|
15 | 16 |
|
16 | 17 | /**
|
|
19 | 20 |
|
20 | 21 | public class Test2 {
|
21 | 22 |
|
22 |
| - public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { |
23 |
| - HashMap<String, HashMap<String, Double>> valueMap = new HashMap<>(); |
24 |
| - |
25 |
| - for (int i = 0; i < equations.length; i++) { |
26 |
| - String[] equation = equations[i]; |
27 |
| - HashMap<String, Double> map = valueMap.computeIfAbsent(equation[0], k -> new HashMap<>()); |
28 |
| - map.put(equation[1], values[i]); |
29 |
| - map = valueMap.computeIfAbsent(equation[1], k -> new HashMap<>()); |
30 |
| - map.put(equation[0], 1 / values[i]); |
| 23 | + public int countComponents2(int n, int[][] edges) { |
| 24 | + List<Integer>[] graph = new ArrayList[n]; |
| 25 | + for (int i = 0; i < n; i++) { |
| 26 | + graph[i] = new ArrayList<>(); |
31 | 27 | }
|
32 |
| - |
33 |
| - double[] result = new double[queries.length]; |
34 |
| - for (int i = 0; i < queries.length; i++) { |
35 |
| - double[] value = new double[] {1.0}; |
36 |
| - result[i] = dfs(valueMap, queries[i][0], queries[i][1], new HashSet<>(), value) ? value[0] : -1.0; |
| 28 | + for (int[] edge : edges) { |
| 29 | + graph[edge[0]].add(edge[1]); |
| 30 | + graph[edge[1]].add(edge[0]); |
| 31 | + } |
| 32 | + Set<Integer> visited = new HashSet<>(); |
| 33 | + int count = 0; |
| 34 | + for (int i = 0; i < n; i++) { |
| 35 | + if (!visited.contains(i)) { |
| 36 | + count++; |
| 37 | + dfs(graph, i, visited); |
| 38 | + } |
37 | 39 | }
|
38 |
| - return result; |
| 40 | + return count; |
39 | 41 | }
|
40 | 42 |
|
41 |
| - private boolean dfs(HashMap<String, HashMap<String, Double>> map, String start, String end, HashSet<String> set, double[] value) { |
42 |
| - if (!map.containsKey(start) || !map.containsKey(end) || set.contains(start)) { |
43 |
| - return false; |
44 |
| - } |
45 |
| - if (start.equals(end)) { |
46 |
| - return true; |
| 43 | + private void dfs(List<Integer>[] graph, int i, Set<Integer> visited) { |
| 44 | + if (!visited.add(i)) { |
| 45 | + return; |
47 | 46 | }
|
48 |
| - set.add(start); |
49 |
| - HashMap<String, Double> valueMap = map.get(start); |
50 |
| - boolean flag = false; |
51 |
| - for (Map.Entry<String, Double> entry : valueMap.entrySet()) { |
52 |
| - value[0] *= entry.getValue(); |
53 |
| - if (dfs(map, entry.getKey(), end, set, value)) { |
54 |
| - flag = true; |
55 |
| - break; |
56 |
| - } |
57 |
| - value[0] /= entry.getValue(); |
| 47 | + for (Integer k : graph[i]) { |
| 48 | + dfs(graph, k, visited); |
58 | 49 | }
|
59 |
| - set.remove(start); |
60 |
| - return flag; |
61 | 50 | }
|
62 | 51 | }
|
0 commit comments