Description
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.
在节点网络中,只有当 graph[i][j] = 1 时,每个节点 i 能够直接连接到另一个节点 j。
一些节点 initial 最初被恶意软件感染。只要两个节点直接连接,且其中至少一个节点受到恶意软件的感染,那么两个节点都将被恶意软件感染。这种恶意软件的传播将继续,直到没有更多的节点可以被这种方式感染。
假设 M(initial) 是在恶意软件停止传播之后,整个网络中感染恶意软件的最终节点数。
我们可以从初始列表中删除一个节点。如果移除这一节点将最小化 M(initial), 则返回该节点。如果有多个节点满足条件,就返回索引最小的节点。
请注意,如果某个节点已从受感染节点的列表 initial 中删除,它以后可能仍然因恶意软件传播而受到感染。
题目链接:https://leetcode.com/problems/minimize-malware-spread/description/
Difficulty: hard
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
分析
- 定义dfs(index)为深度遍历函数,返回新感染的结点总数,self.gra存储每个结点的感染状态(1为感染,0为未感染);
- dfs从初始结点i开始,遍历所有剩下结点j,若graph[i][j]==1(i,j相连),则j被感染,以j为初始结点,进入下一层深度遍历,直至所有相连结点都被感染;
- 遍历initial,即去除当前结点i的感染状态,初始化self.gra,遍历除了i结点外initial中所有结点,作为初始结点,深度遍历,返回新感染的结点个数;
- 得到返回新感染节点个数最小的对应的去除的结点,即使需要得到的结果;
- 题目中要求返回最小的结点序号,可以对initial排序之后再处理。
参考代码
class Solution:
def minMalwareSpread(self, graph, initial):
length=len(graph[0])
def dfs(index):
s=0
for j in range(length):
if(index != j):
if(graph[index][j]==1 and self.gra[j]==0):
self.gra[j]=1
s+=(dfs(j)+1)
return s
index =length
initial.sort()
target=initial[0]
for i in initial:
self.gra=[0]*length
for tar in initial:
if(tar!=i):
self.gra[tar]=1
curr=0
for tar in initial:
if(tar!=i):
curr+=dfs(tar)
if(curr < index):
target=i
index=curr
return target