File tree 1 file changed +45
-0
lines changed
1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } graph
3
+ * @param {number[] } initial
4
+ * @return {number }
5
+ */
6
+ var minMalwareSpread = function ( graph , initial ) {
7
+ const map = new Map ( ) // node -> initial nodes infect this node
8
+ for ( let i of initial ) {
9
+ const visited = new Set ( initial )
10
+ const q = [ ]
11
+ q . push ( i )
12
+ while ( q . length ) {
13
+ let cur = q . shift ( )
14
+ for ( let j = 0 ; j < graph [ cur ] . length ; j ++ ) {
15
+ if ( graph [ cur ] [ j ] == 1 ) {
16
+ if ( ! visited . has ( j ) ) {
17
+ visited . add ( j )
18
+ q . push ( j )
19
+
20
+ if ( map . get ( j ) == null ) map . set ( j , [ ] )
21
+ map . get ( j ) . push ( i )
22
+ }
23
+ }
24
+ }
25
+ }
26
+ }
27
+
28
+ const res = Array ( graph . length ) . fill ( 0 ) // node -> safe nodes it infects
29
+ for ( let node of map . keys ( ) ) {
30
+ if ( map . get ( node ) . length == 1 ) {
31
+ let i = map . get ( node ) [ 0 ]
32
+ res [ i ] ++
33
+ }
34
+ }
35
+ let max = 0
36
+ let removed = - 1
37
+ for ( let i = 0 ; i < res . length ; i ++ ) {
38
+ if ( res [ i ] > max ) {
39
+ max = res [ i ]
40
+ removed = i
41
+ }
42
+ }
43
+ initial . sort ( ( a , b ) => a - b )
44
+ return removed == - 1 ? initial [ 0 ] : removed
45
+ }
You can’t perform that action at this time.
0 commit comments