|
| 1 | + |
| 2 | +**坑点**: |
| 3 | + |
| 4 | +1. 不是删除一个顶点,是将一个顶点去除颜色 |
| 5 | + |
| 6 | +# 题目链接 |
| 7 | + |
| 8 | +[minimize-malware-spread](https://leetcode.com/problems/minimize-malware-spread/) |
| 9 | + |
| 10 | + |
| 11 | +# 分析 |
| 12 | + |
| 13 | +了解上面的坑点之后就简单多了 |
| 14 | + |
| 15 | +只有当且仅当一个 initial 点在连通分量中,我们擦除它的颜色才有收益 |
| 16 | + |
| 17 | +# code |
| 18 | + |
| 19 | +```java |
| 20 | +import java.util.*; |
| 21 | +class Solution { |
| 22 | + public int minMalwareSpread(int[][] graph, int[] initial) { |
| 23 | + Arrays.sort(initial); |
| 24 | + int n = graph.length; |
| 25 | + int[] comp = new int[n]; |
| 26 | + int[] candidate = new int[n+1]; |
| 27 | + boolean[] isVal = new boolean[n]; |
| 28 | + for(int i=0 ; i<initial.length ; ++i)isVal[initial[i]] = true; |
| 29 | + int C = 0; |
| 30 | + for(int i=0 ; i<graph.length ; ++i){ |
| 31 | + Queue<Integer> Q = new LinkedList<>(); |
| 32 | + if(comp[i]==0)dfs(i, ++C, comp, graph,Q,isVal); |
| 33 | + if(Q.size() == 1){ |
| 34 | + candidate[C] = Q.remove()+1; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + int[] cnt = new int[C+1]; |
| 39 | + for(int i=0 ; i<n ; ++i)cnt[comp[i]]++; |
| 40 | + int val = 0,ans = 0; |
| 41 | + for(int i=1 ; i <=C ; ++i) |
| 42 | + if(candidate[i]!=0){ |
| 43 | + if(cnt[i] > val|| (cnt[i] == val && ans > candidate[i])){ |
| 44 | + ans = candidate[i]; |
| 45 | + val = cnt[i]; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + if(ans !=0)return ans -1; |
| 50 | + else return initial[0]; |
| 51 | + |
| 52 | + } |
| 53 | + private void dfs(int u, int col,int[] comp,int[][] g, Collection<Integer> black,boolean[] isVal) { |
| 54 | + comp[u] = col; |
| 55 | + if(isVal[u])black.add(u); |
| 56 | + for(int i=0 ; i< comp.length ; ++i) |
| 57 | + if(g[u][i]==1 &&comp[i]==0)dfs(i, col, comp,g,black,isVal); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +``` |
| 62 | + |
| 63 | + |
0 commit comments