Given a directed acyclic graph, with
Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
n
vertices numbered from 0
to n-1
, and an array edges
where edges[i] = [fromi, toi]
represents a directed edge from node fromi
to node toi
.Find the smallest set of vertices from which all nodes in the graph are reachable. It's guaranteed that a unique solution exists.
Notice that you can return the vertices in any order.
Example 1:
Input: n = 6, edges = [[0,1],[0,2],[2,5],[3,4],[4,2]]
Output: [0,3]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class MinNumVerticesReachNode {public static void main(String[] args) {int n = 6;int[][] edges = { { 0, 1 }, { 0, 2 }, { 2, 5 }, { 3, 4 }, { 4, 2 } };List<Integer> ans = findSmallestSetOfVertices(n, edges);System.out.println(Arrays.asList(ans));}static List<Integer> findSmallestSetOfVertices(int n, int[][] edges) {List<Integer> res = new ArrayList<Integer>();int indegree[] = new int[n];for (int i = 0; i < n; i++)indegree[i] = 0;for (int i = 0; i < edges.length; i++) {int y = edges[i][1];indegree[y]++;}for (int i = 0; i < n; i++)if (indegree[i] == 0)res.add(i);return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> findSmallestSetOfVertices(int n, vector<vector<int>> &edges){vector<int> res;int indegree[n];for (int i = 0; i < n; i++)indegree[i] = 0;for (int i = 0; i < edges.size(); i++){int x = edges[i][0];int y = edges[i][1];indegree[y]++;}for (int i = 0; i < n; i++)if (indegree[i] == 0)res.push_back(i);return res;}int main(){int n = 6;vector<vector<int>> edges = {{0, 1}, {0, 2}, {2, 5},{3, 4}, {4, 2}};vector<int> ans = findSmallestSetOfVertices(n, edges);cout << "[";for (int i = 0; i < ans.size() - 1; i++){cout << ans[i] << ",";}cout << ans[ans.size() - 1] << "]";return 0;}
No comments:
Post a Comment