LeetCode之Find Eventual Safe States(Kotlin)

問題: 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. node

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表明安全節點,子節點存在非安全節點則爲非安全節點,不然爲安全節點,保存全部的安全節點即爲最終結果。git

具體實現:github

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安全

相關文章
相關標籤/搜索