File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const input = require ( 'fs' )
2+ . readFileSync ( process . platform === 'linux' ? '/dev/stdin' : './input.txt' )
3+ . toString ( )
4+ . trim ( )
5+ . split ( '\n' )
6+ . map ( ( el ) => el . split ( ' ' ) ) ;
7+
8+ function solution ( input ) {
9+ const T = Number ( input [ 0 ] [ 0 ] ) ;
10+ let index = 1 ;
11+ const result = [ ] ;
12+ const dx = [ - 1 , 1 , 0 , 0 ] ;
13+ const dy = [ 0 , 0 , - 1 , 1 ] ;
14+
15+ for ( let i = 0 ; i < T ; i ++ ) {
16+ const [ H , W ] = input [ index ] . map ( ( el ) => Number ( el ) ) ;
17+ const sheeps = input
18+ . slice ( index + 1 , index + 1 + H )
19+ . map ( ( row ) => row . join ( '' ) . split ( '' ) ) ;
20+
21+ index += H + 1 ;
22+
23+ let count = 0 ;
24+ function dfs ( x , y ) {
25+ sheeps [ x ] [ y ] = '.' ;
26+ for ( let i = 0 ; i < 4 ; i ++ ) {
27+ const nx = x + dx [ i ] ;
28+ const ny = y + dy [ i ] ;
29+ if ( nx >= 0 && nx < H && ny >= 0 && ny < W && sheeps [ nx ] [ ny ] === '#' ) {
30+ dfs ( nx , ny ) ;
31+ }
32+ }
33+ }
34+
35+ for ( let i = 0 ; i < H ; i ++ ) {
36+ for ( let j = 0 ; j < W ; j ++ ) {
37+ if ( sheeps [ i ] [ j ] === '#' ) {
38+ count ++ ;
39+ dfs ( i , j ) ;
40+ }
41+ }
42+ }
43+ result . push ( count ) ;
44+ }
45+ return result . join ( '\n' ) ;
46+ }
47+
48+ console . log ( solution ( input ) ) ;
You can’t perform that action at this time.
0 commit comments