File tree 1 file changed +63
-0
lines changed
1 file changed +63
-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
+ const minMalwareSpread = function ( graph , initial ) {
7
+ const l = graph . length
8
+ const p = [ ]
9
+ const children = [ ]
10
+ for ( let i = 0 ; i < l ; i ++ ) {
11
+ p [ i ] = i
12
+ children [ i ] = [ i ]
13
+ }
14
+
15
+ for ( let i = 0 ; i < l ; i ++ ) {
16
+ for ( let j = i + 1 ; j < l ; j ++ ) {
17
+ if ( graph [ i ] [ j ] === 1 ) {
18
+ const pi = find ( i )
19
+ const pj = find ( j )
20
+ if ( pi !== pj ) {
21
+ union ( pi , pj )
22
+ }
23
+ }
24
+ }
25
+ }
26
+
27
+ initial . sort ( ( a , b ) => ( a > b ? 1 : - 1 ) )
28
+
29
+ const count = { }
30
+
31
+ let index = initial [ 0 ]
32
+ let max = 0
33
+ // find the index that not unioned with other indexes and with the most number of children
34
+ initial . forEach ( ( e ) => {
35
+ const pe = find ( e )
36
+ if ( ! count [ pe ] ) count [ pe ] = 0
37
+ count [ pe ] += 1
38
+ } )
39
+ initial . forEach ( ( e , i ) => {
40
+ const pe = find ( e )
41
+ if ( count [ pe ] === 1 && children [ pe ] . length > max ) {
42
+ max = children [ pe ] . length
43
+ index = e
44
+ }
45
+ } )
46
+
47
+ return index
48
+
49
+ function find ( x ) {
50
+ while ( p [ x ] !== x ) {
51
+ p [ x ] = p [ p [ x ] ]
52
+ x = p [ x ]
53
+ }
54
+ return x
55
+ }
56
+
57
+ function union ( pi , pj ) {
58
+ p [ pj ] = pi
59
+ //also move the children to the new parent
60
+ children [ pi ] = children [ pi ] . concat ( children [ pj ] )
61
+ children [ pj ] = [ ]
62
+ }
63
+ }
You can’t perform that action at this time.
0 commit comments