Daily LeetCode Challenge - 1557. Minimum Number of Vertices to Reach All Nodes

Min Young Kim·2023년 5월 18일
0

algorithm

목록 보기
149/198

Problem From.

https://leetcode.com/problems/minimum-number-of-vertices-to-reach-all-nodes/

오늘 문제는 그래프가 주어졌을때, 시작점에서 탐색을 시작하고 모든 노드를 탐색할 수 있는 시작점들의 최솟값을 구하는 문제였다.

문제는 간단하게 풀 수 있었는데, 시작점은 들어오는 방향이 없는 노드를 의미한다. 들어오는 방향이 있는 노드는 어딘가에서 도달할 수 있다는 의미이므로, 도달할 수 없는 들어오는 방향이 없는 노드 갯수를 세서 반환하면 되는 문제였다.

class Solution {
    fun findSmallestSetOfVertices(n: Int, edges: List<List<Int>>): List<Int> {
        
        val set = hashSetOf<Int>()
        
        for(i in 0 until n) {
            set.add(i)
        }
        
        edges.forEach {
            if(set.contains(it[1])) set.remove(it[1])
        }
        
        return set.toList()
    }
}
profile
길을 찾는 개발자

0개의 댓글