LeetCode in Kotlin

928. Minimize Malware Spread II

Hard

You are given a network of n nodes represented as an n x n adjacency matrix graph, where the ith node is directly connected to the jth node if graph[i][j] == 1.

Some nodes initial are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.

Suppose M(initial) is the final number of nodes infected with malware in the entire network after the spread of malware stops.

We will remove exactly one node from initial, completely removing it and any connections from this node to any other node.

Return the node that, if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.

Example 1:

Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]

Output: 0

Example 2:

Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]

Output: 1

Example 3:

Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]

Output: 1

Constraints:

Solution

import java.util.LinkedList
import java.util.Queue

class Solution {
    private val adj: MutableMap<Int, ArrayList<Int>> = HashMap()
    private var visited: MutableSet<Int>? = null
    private var count = 0

    private fun bfs(ind: Int, initial: IntArray) {
        val q: Queue<Int> = LinkedList()
        for (i in initial.indices) {
            if (i != ind) {
                q.add(initial[i])
                visited!!.add(initial[i])
            }
        }
        while (q.isNotEmpty()) {
            val curr = q.poll()
            if (curr != initial[ind]) {
                count++
            }
            val children = adj[curr]
            if (children != null) {
                for (child in children) {
                    if (!visited!!.contains(child)) {
                        q.add(child)
                        visited!!.add(child)
                    }
                }
            }
        }
    }

    fun minMalwareSpread(graph: Array<IntArray>, initial: IntArray): Int {
        val n = graph.size
        for (i in 0 until n) {
            adj.putIfAbsent(i, ArrayList())
            for (j in 0 until n) {
                if (graph[i][j] == 1) {
                    adj.getValue(i).add(j)
                }
            }
        }
        var min = n + 1
        initial.sort()
        var node = initial[0]
        for (i in initial.indices) {
            visited = HashSet()
            val children = adj.getValue(initial[i])
            adj.remove(initial[i])
            bfs(i, initial)
            if (count < min) {
                min = count
                node = initial[i]
            }
            count = 0
            adj[initial[i]] = children
        }
        return node
    }
}