File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ class SolutionNumberOfIslands {
2+ char [][] sharedGrid ;
3+ int [] dx = new int []{0 , 0 , -1 , 1 };
4+ int [] dy = new int []{-1 , 1 , 0 , 0 };
5+
6+ public int numIslands (char [][] grid ) {
7+ // νμ΄
8+ // λ€ λͺ¨μλ¦¬κ° λ¬Όλ‘ λλ¬μμ¬μμΌλ©΄ μμΌλλ
9+ // μμΌλλμ κ°μλ₯Ό λ°νν΄λΌ
10+ // λ
μΈ κ²½μ° DFS λλ €μ μννμ
11+ // μνμ’μ° νμΈνλ©΄μ λ
μ΄λ©΄ λ¬Όλ‘ λ³κ²½νλ©΄μ μννλ€
12+ // DFS 1ν λΉ answer += 1
13+ // TC: O(N), Nμ λ°°μ΄ μμ κ°μ
14+ // SC: O(N)
15+ var answer = 0 ;
16+
17+ sharedGrid = grid ;
18+ for (int i =0 ; i <grid .length ; i ++) {
19+ for (int j =0 ; j <grid [0 ].length ; j ++) {
20+ if (sharedGrid [i ][j ] == '1' ) {
21+ dfs (i , j );
22+ answer ++;
23+ }
24+ }
25+ }
26+
27+ return answer ;
28+ }
29+
30+ private void dfs (int i , int j ) {
31+ sharedGrid [i ][j ] = '0' ;
32+
33+ for (int k =0 ; k <4 ; k ++) {
34+ var x = i +dx [k ];
35+ var y = j +dy [k ];
36+ if (x >= 0 && y >= 0 && x < sharedGrid .length && y < sharedGrid [0 ].length && sharedGrid [x ][y ] == '1' ) {
37+ dfs (x , y );
38+ }
39+ }
40+ }
41+ }
You canβt perform that action at this time.
0 commit comments