LC每日一题|20240404 - 2192. 有向无环图中一个节点的所有祖先

98 阅读1分钟

LC每日一题|20240404 - 2192. 有向无环图中一个节点的所有祖先

给你一个正整数 n ,它表示一个 有向无环图 中节点的数目,节点编号为 0 到 n - 1 (包括两者)。

给你一个二维整数数组 edges ,其中 edges[i] = [fromi, toi] 表示图中一条从 fromi 到 toi 的单向边。

请你返回一个数组 answer,其中 **answer[i]是第 i 个节点的所有 祖先 ,这些祖先节点 升序 排序。

如果 u 通过一系列边,能够到达 v ,那么我们称节点 u 是节点 v 的 祖先 节点。

提示:

  • 1 <= n <= 1000
  • 0 <= edges.length <= min(2000, n * (n - 1) / 2)
  • edges[i].length == 2
  • 0 <= fromi, toi <= n - 1
  • fromi != toi
  • 图中不会有重边。
  • 图是 有向无环 的。

题目级别: Medium

今天脑子明显不太好使...

其实这道题是挺简单的,直接一手BFS,入度为0的节点可以做根入队列,遍历的过程中将父节点的res + cur都扔给子节点就完事了,用set去重,最后记得排个序~

class Solution {
    fun getAncestors(n: Int, edges: Array<IntArray>): List<List<Int>> {
        val res = Array<HashSet<Int>>(n) { hashSetOf() }
        val map = Array<ArrayList<Int>>(n) { arrayListOf() }   //邻接表
        val degree = IntArray(n)  //入度
        for (edge in edges) { 
            map[edge[0]].add(edge[1])
            degree[edge[1]] ++
        }
        
    
        val queue = ArrayDeque<Int>()
        for (i in degree.indices) if (degree[i] == 0) queue.addLast(i)
        while (queue.isNotEmpty()) {
            repeat(queue.size) {
                val node = queue.removeFirst()
                map[node].forEach {
                    res[it].add(node)
                    res[it].addAll(res[node])
                    degree[it]--
                    if (degree[it] == 0) queue.addLast(it)
                }
            }
        }

        return res.map { it.toList().sorted() }.toList()
    }
}

这几天在准备面试,发现自己真的有好多的天坑啊...好慌...