3372. Maximize the Number of Target Nodes After Connecting Trees I
Intuition\n Describe your first thoughts on how to solve this problem. \nGiven two trees, T1 and T2, and an integer k, we want to find the maximum number of nod
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGiven two trees, T1 and T2, and an integer k, we want to find the maximum number of nodes in T1 that are at most k edges away from each node i in T1 after connecting i to a node in T2.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each tree, calculate the distance from each node to all other nodes. This can be done using a simple Breadth-First Search (BFS) traversal.\nStore the distances in a 2D matrix for each tree.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n    public int[] maxTargetNodes(int[][] edges1, int[][] edges2, int k) {\n        int n = edges1.length + 1, m = edges2.length + 1;\n        List<Integer>[] adj = new List[m];\n        for (int i = 0; i < m; i++) {\n            adj[i] = new ArrayList<>();\n        }\n        for (int[] e : edges2) {\n            adj[e[0]].add(e[1]);\n            adj[e[1]].add(e[0]);\n        }\n        int max = 0;\n        for (int i = 0; i < m; i++) {\n            max = Math.max(max, bfs(adj, m, i, k - 1));\n        }\n        adj = new List[n];\n        for (int i = 0; i < n; i++) {\n            adj[i] = new ArrayList<>();\n        }\n        for (int[] e : edges1) {\n            adj[e[0]].add(e[1]);\n            adj[e[1]].add(e[0]);\n        }\n        int[] res = new int[n];\n        for (int i = 0; i < n; i++) {\n            res[i] = bfs(adj, n, i, k) + max;\n        }\n        return res;\n    }\n\n    static int bfs(List<Integer>[] adj, int n, int start, int k) {\n        if (k < 0) {\n            return 0;\n        }\n        boolean[] seen = new boolean[n];\n        Queue<Integer> q = new LinkedList<>();\n        q.add(start);\n        seen[start] = true;\n        int res = 0, step = 0;\n        while (!q.isEmpty() && step <= k) {\n            int sz = q.size();\n            res += sz;\n            for (int i = 0; i < sz; i++) {\n                int node = q.poll();\n                for (int neighbor : adj[node]) {\n                    if (!seen[neighbor]) {\n                        seen[neighbor] = true;\n                        q.add(neighbor);\n                    }\n                }\n            }\n            step++;\n        }\n        return res;\n    }\n    \n}\n```
['Java']