File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } mat
3
+ * @return {number }
4
+ */
5
+ const minFlips = function ( mat ) {
6
+ const X = mat . length
7
+ const Y = mat [ 0 ] . length
8
+ const binary = {
9
+ 0 : 1 ,
10
+ 1 : 2 ,
11
+ 2 : 4 ,
12
+ 3 : 8 ,
13
+ 4 : 16 ,
14
+ 5 : 32 ,
15
+ 6 : 64 ,
16
+ 7 : 128 ,
17
+ 8 : 256 ,
18
+ }
19
+ const mask = [ ]
20
+ let state = 0
21
+ for ( let i = 0 ; i < X ; ++ i ) {
22
+ for ( let j = 0 ; j < Y ; ++ j ) {
23
+ let bit = 0
24
+ state += mat [ i ] [ j ] * binary [ Y * i + j ]
25
+ bit += binary [ Y * i + j ]
26
+ if ( i > 0 ) {
27
+ bit += binary [ Y * ( i - 1 ) + j ]
28
+ }
29
+ if ( i < X - 1 ) {
30
+ bit += binary [ Y * ( i + 1 ) + j ]
31
+ }
32
+ if ( j > 0 ) {
33
+ bit += binary [ Y * i + ( j - 1 ) ]
34
+ }
35
+ if ( j < Y - 1 ) {
36
+ bit += binary [ Y * i + ( j + 1 ) ]
37
+ }
38
+ mask . push ( bit )
39
+ }
40
+ }
41
+ if ( state === 0 ) {
42
+ return 0
43
+ }
44
+ const set = new Set ( )
45
+ const q = [ { state : state , moves : 0 } ]
46
+ while ( q . length !== 0 ) {
47
+ const cur = q . shift ( )
48
+ if ( cur . state === 0 ) {
49
+ return cur . moves
50
+ }
51
+ for ( let i = 0 ; i < X * Y ; ++ i ) {
52
+ let newState = cur . state
53
+ newState ^= mask [ i ]
54
+ if ( ! set . has ( newState ) ) {
55
+ set . add ( newState )
56
+ q . push ( { state : newState , moves : cur . moves + 1 } )
57
+ }
58
+ }
59
+ }
60
+ return - 1
61
+ }
You can’t perform that action at this time.
0 commit comments