halfrost/LeetCode-Go

Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
..
Failed to load latest commit information.

题目:

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. `1 < graph.length = graph[0].length <= 300`
2. `0 <= graph[i][j] == graph[j][i] <= 1`
3. `graph[i][i] = 1`
4. `1 <= initial.length < graph.length`
5. `0 <= initial[i] < graph.length`

题目大意

• 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

解题思路

• 给出一个节点之间的关系图，如果两个节点是连通的，那么病毒软件就会感染到连通的所有节点。现在如果想移除一个病毒节点，能最大减少感染，请问移除哪个节点？如果多个节点都能减少感染量，优先移除序号偏小的那个节点。
• 这一题一看就是考察的并查集。利用节点的连通关系，把题目中给的所有节点都 `union()` 起来，然后依次统计每个集合内有多少个点。最后扫描一次 initial 数组，选出这个数组中节点小的并且所在集合节点多，这个节点就是最终答案。
You can’t perform that action at this time.