@@ -31,3 +31,64 @@ function search(board, i, j) {
31
31
search ( board , i , j + 1 ) ;
32
32
search ( board , i , j - 1 ) ;
33
33
}
34
+
35
+ // another
36
+
37
+ /**
38
+ * @param {character[][] } board
39
+ * @return {void } Do not return anything, modify board in-place instead.
40
+ */
41
+ const solve = ( board ) => {
42
+ if ( ! board || board . length === 0 || board [ 0 ] . length === 0 ) return ;
43
+ const n = board . length ;
44
+ const m = board [ 0 ] . length ;
45
+ const dirs = [
46
+ [ - 1 , 0 ] ,
47
+ [ 1 , 0 ] ,
48
+ [ 0 , - 1 ] ,
49
+ [ 0 , 1 ] ,
50
+ ] ;
51
+ const bfs = ( board , n , m , i , j ) => {
52
+ const queue = [ ] ;
53
+ queue . push ( [ i , j ] ) ;
54
+ board [ i ] [ j ] = "1" ;
55
+ while ( queue . length > 0 ) {
56
+ const pos = queue . shift ( ) ;
57
+ for ( let k = 0 ; k < 4 ; k ++ ) {
58
+ i = pos [ 0 ] + dirs [ k ] [ 0 ] ;
59
+ j = pos [ 1 ] + dirs [ k ] [ 1 ] ;
60
+ if ( i >= 0 && i < n && j >= 0 && j < m && board [ i ] [ j ] === "O" ) {
61
+ board [ i ] [ j ] = "1" ;
62
+ queue . push ( [ i , j ] ) ;
63
+ }
64
+ }
65
+ }
66
+ } ;
67
+ // scan the borders and mark the 'O's to '1'
68
+ for ( let i = 0 ; i < n ; i ++ ) {
69
+ for ( let j = 0 ; j < m ; j ++ ) {
70
+ if (
71
+ ( i === 0 || i === n - 1 || j === 0 || j === m - 1 ) &&
72
+ board [ i ] [ j ] === "O"
73
+ ) {
74
+ bfs ( board , n , m , i , j ) ;
75
+ }
76
+ }
77
+ }
78
+ // scan the inner area and mark the 'O's to 'X'
79
+ for ( let i = 1 ; i < n ; i ++ ) {
80
+ for ( let j = 1 ; j < m ; j ++ ) {
81
+ if ( board [ i ] [ j ] === "O" ) {
82
+ board [ i ] [ j ] = "X" ;
83
+ }
84
+ }
85
+ }
86
+ // reset all the '1's to 'O's
87
+ for ( let i = 0 ; i < n ; i ++ ) {
88
+ for ( let j = 0 ; j < m ; j ++ ) {
89
+ if ( board [ i ] [ j ] === "1" ) {
90
+ board [ i ] [ j ] = "O" ;
91
+ }
92
+ }
93
+ }
94
+ } ;
0 commit comments