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, 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
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
与Minimizie Malware spread 不同的是,这次是将初始被感染的电脑 以及 其连接关系完全在网络中移除。考虑其数据规模,可以选择 枚举移除元素 求解。
采用DFS实现这个算法。记辅助数组 vis[i] ,其中 i 是表示节点 i ,数组中记录这个节点是否已经被访问过。首先选取一个初始被感染的点作为被移除的点,之后计算当这个点被移除时,将有多少点被感染。依次选取初始被感染的点移除,记录移除后被感染最少的节点,相同时,记节点编号最小的点
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int len=initial.size();
int sum=graph.size();
int num;
vector<bool> vis(sum,false);
int ans=0,peak=INT_MIN;
for(int i=0;i<len;i++){
num=0;
ini(vis,sum);
for(int j=0;j<len;j++){
if(j==i || vis[initial[j]])
continue;
vis[initial[j]]=true;
num+=cal(graph,initial[j],initial[i],vis)+1;
}
//printf("sum-num=%d\n",sum-num);
if(peak < (sum-num) ){
peak=sum-num;
ans=i;
}else{
if(peak==(sum-num) && initial[ans]>initial[i])
ans=i;
}
}
return initial[ans];
}
void ini(vector<bool>& vis,int len){
for(int i=0;i<len;i++)
vis[i]=false;
}
int cal(vector<vector<int> >& graph,int star,int node,vector<bool>& vis){
int infectNum=0;
int len=graph.size();
bool change=false;
for(int i=0;i<len;i++){
if(graph[star][i]==0 || i==node || vis[i])
continue;
change=true;
vis[i]=true;
infectNum+=cal(graph,i,node,vis)+1;
}
if(!change)
return 0;
return infectNum;
}
};