# 924.Minimize-Malware-Spread

## 924. Minimize Malware Spread

## 题目地址

<https://leetcode.com/problems/minimize-malware-spread/>

## 题目描述

```
In a network of nodes, each node i is directly connected to another node j if and only 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 one node from the initial list.  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.

Note that if a node was removed from the initial list of infected nodes, it may still be infected later as a result of the malware spread.

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

Example 2:
Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0

Example 3:
Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1

Note:
1 < graph.length = graph[0].length <= 300
0 <= graph[i][j] == graph[j][i] <= 1
graph[i][i] == 1
1 <= initial.length <= graph.length
0 <= initial[i] < graph.length
```

## 代码

### Approach #1 DFS

Time: O(N^2) && Space: O(N)

**Algorithm**

This algorithm has a few parts:

* **Coloring each component:** For each node, if it isn't yet colored, use a depth-first search to traverse its component, coloring that component with a new color.
* **Size of each color:** Count the number of occurrences of each color.
* **Find unique colors:** Look at the colors of nodes in `initial` to see which nodes have unique colors.
* **Choose answer:** For each node with a unique color, find the size of that color. The largest size is selected, with ties broken by lowest node number.
  * If there is no node with a unique color, the answer is `min(initial)`.

```java
class Solution {
    public int minMalwareSpread(int[][] graph, int[] initial) {
        int n = graph.length;
        int color = 0; 
        int[] colors = new int[n];
        Arrays.fill(colors, -1);

       // 1. Color each component.
        for (int node = 0; node < n; node++) {
            if (colors[node] == -1) {
                colors[node] = ++color;
                dfs(graph, node, colors, color);   
            }
        }

        // 2. Size of each color.
        int[] size = new int[color + 1];
        for (int c : colors) {
            size[c]++;
        }

        // 3. Find unique colors.
        int[] colorCount = new int[color+1];
        for (int node : initial) {
            int c = colors[node];
            colorCount[c]++;
        }

         // 4. Answer
        int ans = Integer.MAX_VALUE;
        for (int node: initial) {
            int c = colors[node];
            if (colorCount[c] == 1) {
               if (ans == Integer.MAX_VALUE) {
                   ans = node;
               } else if (size[c] > size[colors[ans]]) {
                   ans = node;
               } else if (size[c] == size[colors[ans]] && node < ans){
                    ans = node;               
               }
           }
        }

        if (ans == Integer.MAX_VALUE) {
            for (int node: initial) {
                ans = Math.min(ans, node);
            }
        }
        return ans;
    }

    private void dfs(int[][] graph, int node, int[] colors, int color) {
        int n = graph.length;
        for (int i = 0; i < n; i++) {
            if (graph[node][i] == 1 && colors[i] == -1) {
                colors[i] = color;
                dfs(graph, i, colors, color);
            }
        }
    }

}
```

### Approach #2 Union-Find

`Time: O(N^2) && Space: O(N)`

```java
class Solution {
    public int minMalwareSpread(int[][] graph, int[] initial) {
        int n = graph.length;
        DSU dsu = new DSU(n);
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                if (graph[i][j] == 1) {
                    dsu.union(i, j);
                }
            } 
        }


        int[] count = new int[n];
        for (int node: initial) {
            int root = dsu.find(node);
            count[root]++;
        }


        int ans = -1;
        for (int node: initial) {
            int root = dsu.find(node);
            if (count[root] == 1) {
                if (ans == -1) {
                    ans = node;
                } else if (dsu.size(ans) < dsu.size(node)) {
                    ans = node;
                } else if (dsu.size(ans) == dsu.size(node) && node < ans) {
                    ans = node;
                }
            }
        }

        if (ans == -1) {
            ans = Integer.MAX_VALUE;
            for (int node: initial) {
                ans = Math.min(ans, node);
            }
        }

        return ans;
    }

    class DSU {
        int[] p;
        int[] rank;

        public DSU(int n) {
            p = new int[n];
            rank = new int[n];

            for (int i = 0; i < n; i++) {
                p[i] = i;
            }

            Arrays.fill(rank, 1);
        } 

        public int find(int x) {
            if (x != p[x]) {
                p[x] = find(p[x]);
            }
            return p[x];
        }

        public void union(int x, int y) {
            int n1 = find(x);
            int n2 = find(y);
            if (n1 != n2) {
                p[n1] = n2;
                rank[n2] += rank[n1];
            }
        }


        public int size(int x) {
            int root = find(x);
            return rank[root];
        }

    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/union-find/924.minimize-malware-spread.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
