File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/number-of-islands/
3+ * @param {character[][] } grid
4+ * @return {number }
5+ */
6+ var numIslands = function ( grid ) {
7+ if ( ! grid || grid . length === 0 ) return 0 ;
8+
9+ const rows = grid . length ;
10+ const cols = grid [ 0 ] . length ;
11+ let count = 0 ;
12+
13+ const dfs = ( r , c ) => {
14+ // 경계 밖이거나 물인 경우 리턴
15+ if ( r < 0 || c < 0 || r >= rows || c >= cols || grid [ r ] [ c ] === "0" ) {
16+ return ;
17+ }
18+
19+ // 방문 표시 (육지를 물로 바꿈)
20+ grid [ r ] [ c ] = "0" ;
21+
22+ // 상하좌우 탐색
23+ dfs ( r - 1 , c ) ; // 위
24+ dfs ( r + 1 , c ) ; // 아래
25+ dfs ( r , c - 1 ) ; // 왼쪽
26+ dfs ( r , c + 1 ) ; // 오른쪽
27+ } ;
28+
29+ for ( let r = 0 ; r < rows ; r ++ ) {
30+ for ( let c = 0 ; c < cols ; c ++ ) {
31+ if ( grid [ r ] [ c ] === "1" ) {
32+ count ++ ;
33+ dfs ( r , c ) ; // 해당 섬 전체 방문 처리
34+ }
35+ }
36+ }
37+
38+ return count ;
39+ } ;
You can’t perform that action at this time.
0 commit comments