LeetCode周賽#107 Q4 Minimize Malware Spread II(bfs)
題目來源:https://leetcode.com/contest/weekly-contest-107/problems/minimize-malware-spread-ii/
問題描述
928. Minimize Malware Spread II
(This problem is the same as Minimize Malware Spread, with the differences bolded.)
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
------------------------------------------------------------
題意
類似LeetCode周賽#106 Q4 Minimize Malware Spread (bfs)。給定圖的鄰接矩陣和初始感染節點,問去掉哪個節點(此題的“去掉”是指從圖中刪去該節點而非從初始感染節點集中去掉),最後被感染的節點數最少。定義感染為與感染節點相鄰的節點都會被感染,並具有傳遞性。
------------------------------------------------------------
思路
同LeetCode周賽#106 Q4 Minimize Malware Spread (bfs)。bfs,只是注意bfs的時候永遠不要經過那個被刪去的節點。
------------------------------------------------------------
程式碼
class Solution {
public:
int bfs(vector<vector<int>>& graph, vector<int>& initial, int rem)
{
queue<int> q;
int i, ninit = initial.size(), n = graph.size(), cnt = 0, h;
bool vis[305] = {};
for (i=0; i<ninit; i++)
{
if (i != rem)
{
q.push(initial[i]);
vis[initial[i]] = 1;
cnt++;
}
}
while (!q.empty())
{
h = q.front();
q.pop();
for (i=0; i<n; i++)
{
if (i!=initial[rem] && graph[h][i] == 1 && !vis[i])
{
q.push(i);
vis[i] = 1;
cnt++;
}
}
}
return cnt;
}
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int i, ninit = initial.size(), minv = 0x3f3f3f3f, minid = -1, ans;
sort(initial.begin(), initial.end());
for (i=0; i<ninit; i++)
{
ans = bfs(graph, initial, i);
if (ans < minv)
{
minv = ans;
minid = initial[i];
}
}
return minid;
}
};