LeetCode之Find Eventual Safe States(Kotlin)

498 阅读2分钟

问题: In a directed graph, we start at some node and every turn, walk along a directed edge of the graph. If we reach a node that is terminal (that is, it has no outgoing directed edges), we stop. Now, say our starting node is eventually safe if and only if we must eventually walk to a terminal node. More specifically, there exists a natural number K so that for any choice of where to walk, we must have stopped at a terminal node in less than K steps. Which nodes are eventually safe? Return them as an array in sorted order. The directed graph has N nodes with labels 0, 1, ..., N-1, where N is the length of graph. The graph is given in the following form: graph[i] is a list of labels j such that (i, j) is a directed edge of the graph. Example: Input: graph = [[1,2],[2,3],[5],[0],[5],[],[]] Output: [2,4,5,6] Here is a diagram of the above graph.

image.png

Note:

graph will have length at most 10000.
The number of edges in the graph will not exceed 32000.
Each graph[i] will be a sorted list of different integers, chosen within the range [0, graph.length - 1].

方法: 遍历方式选用深度优先遍历,但是防止重复遍历,需标记已经遍历过得节点,0代表未遍历过,1代表遍历过但非安全节点,2代表安全节点,子节点存在非安全节点则为非安全节点,否则为安全节点,保存所有的安全节点即为最终结果。

具体实现:

class FindEventualSafeStates {
    private lateinit var mColor : Array<Int>
    private lateinit var mGraph : Array<IntArray>

    fun eventualSafeNodes(graph: Array<IntArray>): List<Int> {
        // 图缓存
        mGraph = graph
        // 图着色,0代表未着色,1代表不安全节点,2代表安全节点
        mColor = Array(graph.size, {0})
        return graph.indices.filter { dfs(it) }
    }

    // 深度优先遍历
    private fun dfs(node : Int) : Boolean {
        if (mColor[node] > 0) {
            // 已被着色过返回是否为安全节点
            return mColor[node] == 2
        }
        // 着色
        mColor[node] = 1

        for (subNode in mGraph[node]) {
            val isSafe = dfs(subNode)
            if (!isSafe) {
                // 子节点是非安全节点,则该节点是非安全节点
                return false
            }
        }
        // 所有子节点都是安全节点,则为安全节点
        mColor[node] = 2
        return true
    }
}

// [[1,2,3,4],[1,2],[3,4],[0,4],[]]
fun main(args: Array<String>) {
    val graph = arrayOf(intArrayOf(1, 2, 3, 4), intArrayOf(1, 2), intArrayOf(3, 4), intArrayOf(0, 4), intArrayOf())
    val findEventualSafeStates = FindEventualSafeStates()
    CommonUtils.printArray(findEventualSafeStates.eventualSafeNodes(graph).toTypedArray())
}

有问题随时沟通

具体代码实现可以参考Github