-
157일 (1557. Minimum Number of Vertices to Reach All Nodes) graph, array지식/알고리즘 2024. 2. 24. 13:23
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] Explanation: It's not possible to reach all the nodes from a single vertex. From 0 we can reach [0,1,2,5]. From 3 we can reach [3,4,2,5]. So we output [0,3].
Example 2:
Input: n = 5, edges = [[0,1],[2,1],[3,1],[1,4],[2,4]] Output: [0,2,3] Explanation: Notice that vertices 0, 3 and 2 are not reachable from any other node, so we must include them. Also any of these vertices can reach nodes 1 and 4.
Constraints:
- 2 <= n <= 10^5
- 1 <= edges.length <= min(10^5, n * (n - 1) / 2)
- edges[i].length == 2
- 0 <= fromi, toi < n
- All pairs (fromi, toi) are distinct.
- 접근방법
간단하게 최초로 시작되는 정점만을 List에 담고 리턴하면 된다.
그래프를 이루는 간선은 시작정점과 도착정점으로 이루어져있는데 도착정점이 되지않는 시작정점만을 찾으면 된다.
1. 정점의 개수만큼의 크기로 배열을 초기화한다.
→ 배열의 각 index를 각 정점에 대응시키기 위해 정점의 개수를 배열의 길이로 초기화하였다.
2. 각 정점들이 도착정점에 몇 번 해당되는지 카운트한다.
3. 비순환 그래프 이므로 도착정점에 해당되지 않는 정점은 무조건 최초로 시작되는 정점이 된다.
- 코드
class Solution { public List<Integer> findSmallestSetOfVertices(int n, List<List<Integer>> edges) { List<Integer> answer = new ArrayList<>(); int[] arr = new int[n]; // 1 for(List<Integer> edge: edges) { arr[edge.get(1)]++; } for(int i = 0; i < n; i++) { if(arr[i] == 0) answer.add(i); } return answer; } }
정점의 개수만큼 배열을 초기화하고 그래프의 방향을 배열로 정리하였다.
https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/
Minimum Number of Vertices to Reach All Nodes - LeetCode
Can you solve this real interview question? 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
leetcode.com
'지식 > 알고리즘' 카테고리의 다른 글
159일 (547. Number of Provinces) Graph, DFS (0) 2024.02.26 158일 (841. Keys and Rooms) Graph, DFS (0) 2024.02.25 156일 (1791. Find Center of Star Graph) 그래프, 매우 쉬움 (0) 2024.02.23 155일 (997. Find the Town Judge) 그래프? (0) 2024.02.22 154일 (201. Bitwise AND of Numbers Range) 비트조작 (0) 2024.02.21