Minimum Number of Vertices to Reach All Nodes

Given a directed acyclic graph, with 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 = { { 01 }, { 02 }, { 25 }, { 34 }, { 42 } };
        List<Integerans = findSmallestSetOfVertices(n, edges);
        System.out.println(Arrays.asList(ans));
    }

    static List<IntegerfindSmallestSetOfVertices(int nint[][] edges) {
        List<Integerres = 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<intfindSmallestSetOfVertices(int nvector<vector<int>> &edges)
{
    vector<intres;
    int indegree[n];
    for (int i = 0i < ni++)
        indegree[i] = 0;
    for (int i = 0i < edges.size(); i++)
    {
        int x = edges[i][0];
        int y = edges[i][1];
        indegree[y]++;
    }
    for (int i = 0i < ni++)
        if (indegree[i] == 0)
            res.push_back(i);
    return res;
}

int main()
{
    int n = 6;
    vector<vector<int>> edges = {{01}, {02}, {25}, 
                            {34}, {42}};
    vector<intans = findSmallestSetOfVertices(nedges);
    cout << "[";
    for (int i = 0i < ans.size() - 1i++)
    {
        cout << ans[i] << ",";
    }
    cout << ans[ans.size() - 1] << "]";
    return 0;
}


No comments:

Post a Comment