File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ var solve = function ( board ) {
2+ if ( ! board . length ) return ;
3+
4+ const rows = board . length ;
5+ const cols = board [ 0 ] . length ;
6+ const visited = Array . from ( { length : rows } , ( ) => Array ( cols ) . fill ( false ) ) ;
7+ const dir = [
8+ [ 1 , 0 ] ,
9+ [ - 1 , 0 ] ,
10+ [ 0 , 1 ] ,
11+ [ 0 , - 1 ] ,
12+ ] ;
13+
14+ const bfs = ( r , c ) => {
15+ const queue = [ [ r , c ] ] ;
16+ const path = [ [ r , c ] ] ;
17+ visited [ r ] [ c ] = true ;
18+ let isSurrounded = true ;
19+
20+ while ( queue . length ) {
21+ const [ curY , curX ] = queue . shift ( ) ;
22+
23+ if ( curY === 0 || curY === rows - 1 || curX === 0 || curX === cols - 1 ) {
24+ isSurrounded = false ;
25+ }
26+
27+ for ( let i = 0 ; i < dir . length ; i ++ ) {
28+ const ny = curY + dir [ i ] [ 0 ] ;
29+ const nx = curX + dir [ i ] [ 1 ] ;
30+
31+ if (
32+ ny >= 0 &&
33+ ny < rows &&
34+ nx >= 0 &&
35+ nx < cols &&
36+ board [ ny ] [ nx ] === "O" &&
37+ ! visited [ ny ] [ nx ]
38+ ) {
39+ visited [ ny ] [ nx ] = true ;
40+ queue . push ( [ ny , nx ] ) ;
41+ path . push ( [ ny , nx ] ) ;
42+ }
43+ }
44+ }
45+
46+ if ( isSurrounded ) {
47+ for ( const [ y , x ] of path ) {
48+ board [ y ] [ x ] = "X" ;
49+ }
50+ }
51+ } ;
52+
53+ for ( let i = 0 ; i < rows ; i ++ ) {
54+ for ( let j = 0 ; j < cols ; j ++ ) {
55+ if ( board [ i ] [ j ] === "O" && ! visited [ i ] [ j ] ) {
56+ bfs ( i , j ) ;
57+ }
58+ }
59+ }
60+ } ;
You can’t perform that action at this time.
0 commit comments