LeetCode之Minimize Malware Spread II(Kotlin)

問題: node


方法: 主要是經過DFS遍歷全部節點被移除後的M值,而後經過着色法記錄走過的節點優化時間複雜度。git

具體實現:github

class MinimizeMalwareSpreadII {
    fun minMalwareSpread(graph: Array<IntArray>, initial: IntArray): Int {
        var M = graph.size
        var node = initial[0]
        for (virusRemove in initial) {
            val nodes = IntArray(graph.size) { 0 }
            for (virus in initial) {
                if (virus == virusRemove) {
                    continue
                }
                dfs(graph, virusRemove, nodes, virus)
            }
            if (nodes.sum() < M || (nodes.sum() == M && virusRemove < node)) {
                M = nodes.sum()
                node = virusRemove
            }
        }
        return node
    }

    private fun dfs(graph: Array<IntArray>, virusRemove: Int, nodes: IntArray, virus: Int) {
        if (nodes[virus] == 1) {
            return
        } else {
            nodes[virus] = 1
            for (index in graph[virus].indices) {
                if (graph[virus][index] == 1 && index != virusRemove) {
                    dfs(graph, virusRemove, nodes, index)
                }
            }
        }
    }
}

fun main(args: Array<String>) {
    val graph = arrayOf(intArrayOf(1, 1, 0), intArrayOf(1, 1, 1), intArrayOf(0, 1, 1))
    val initial = intArrayOf(0, 1)
    val minimizeMalwareSpreadII = MinimizeMalwareSpreadII()
    println(minimizeMalwareSpreadII.minMalwareSpread(graph, initial))
}
複製代碼

有問題隨時溝通bash

具體代碼實現能夠參考Github優化

相關文章
相關標籤/搜索