|
| 1 | +public class Solution { |
| 2 | + public List<Integer> findAllPeople(int n, int[][] meetings, int firstPerson) { |
| 3 | + Set<Integer> secrets = new HashSet<>(Arrays.asList(0, firstPerson)); |
| 4 | + Map<Integer, Map<Integer, List<Integer>>> timeMap = new HashMap<>(); |
| 5 | + |
| 6 | + for (int[] meeting : meetings) { |
| 7 | + int src = meeting[0], dst = meeting[1], time = meeting[2]; |
| 8 | + timeMap.putIfAbsent(time, new HashMap<>()); |
| 9 | + timeMap.get(time).putIfAbsent(src, new ArrayList<>()); |
| 10 | + timeMap.get(time).putIfAbsent(dst, new ArrayList<>()); |
| 11 | + timeMap.get(time).get(src).add(dst); |
| 12 | + timeMap.get(time).get(dst).add(src); |
| 13 | + } |
| 14 | + |
| 15 | + for (Integer time : new TreeSet<>(timeMap.keySet())) { |
| 16 | + Set<Integer> visit = new HashSet<>(); |
| 17 | + for (Integer src : timeMap.get(time).keySet()) { |
| 18 | + if (secrets.contains(src)) { |
| 19 | + dfs(src, timeMap.get(time), visit, secrets); |
| 20 | + } |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return new ArrayList<>(secrets); |
| 25 | + } |
| 26 | + |
| 27 | + private void dfs(int src, Map<Integer, List<Integer>> adj, Set<Integer> visit, Set<Integer> secrets) { |
| 28 | + if (visit.contains(src)) { |
| 29 | + return; |
| 30 | + } |
| 31 | + visit.add(src); |
| 32 | + secrets.add(src); |
| 33 | + for (Integer nei : adj.get(src)) { |
| 34 | + dfs(nei, adj, visit, secrets); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public static void main(String[] args) { |
| 39 | + Solution solution = new Solution(); |
| 40 | + int n = 5; |
| 41 | + int[][] meetings = { { 0, 1, 2 }, { 1, 2, 3 }, { 2, 3, 4 }, { 4, 5, 5 } }; |
| 42 | + int firstPerson = 1; |
| 43 | + List<Integer> result = solution.findAllPeople(n, meetings, firstPerson); |
| 44 | + System.out.println(result); |
| 45 | + } |
| 46 | +} |
0 commit comments