File tree 1 file changed +60
-0
lines changed
1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ #해석
2
+ # r,c nested loop로 grid의 모든 element를 검사한다
3
+ # 만약 1인 element를 만나면 sink함수를 호출한다
4
+ # -sink 함수는 해당 element를 0으로 만들고 해당 element의 좌,우,상,하가 1인지 체크한다
5
+ # -만약 1이 있다면 또 sink를 반복 호출하며 위의 검사를 반복한다.(1이 없을때까지)
6
+ # -만약 더이상 연결된 1이 없다면 재귀 호출 종료.
7
+ # sink함수 종료 시시 nested loop로 돌아와서 이후후 1인 element를 찾는다.
8
+ # grid의 1이 sink로 모두 없어지면 return cls한다.
9
+
10
+
11
+ #Big O
12
+ #- M: grid의 행의 갯수(r)
13
+ #- N: grid의 열의 갯수(c)
14
+
15
+ #Time Complexity: O(M*N)
16
+ #- for loop: 이중 루프로 grid의 모든 element에 도달 -> O(M*N)
17
+ #- sink(row,col): 최악의 경우 sink함수는 M*N번 호출 -> O(M*N)
18
+
19
+ #Space Complexity: O(M∗N)
20
+ #- sink 재귀호출:
21
+ # 최악의 경우 sink함수는 스택에 M*N번 재귀 호출 당한다.
22
+ # 스택에 해당 메모리 누적(재귀 호출 스택의 깊이가 M*N) -> O(M*N)
23
+ from typing import List
24
+ class Solution :
25
+ def numIslands (self , grid : List [List [str ]]) -> int :
26
+ def sink (row , col ):
27
+ grid [row ][col ] = "0"
28
+
29
+ for r , c in [
30
+ (row , col - 1 ), #Left
31
+ (row , col + 1 ), #Right
32
+ (row - 1 , col ), #Up
33
+ (row + 1 , col ), #Down
34
+ ]:
35
+ # If the neighbor cell is within bounds and is land ("1"), sink it recursively.
36
+ if 0 <= r < len (grid ) and 0 <= c < len (grid [r ]):
37
+ if grid [r ][c ] == "1" :
38
+ sink (r , c )
39
+
40
+ cnt = 0 # Count the number of islands.
41
+ # Loop through every cell in the grid.
42
+ for r in range (len (grid )):
43
+ for c in range (len (grid [r ])):
44
+ if grid [r ][c ] == "1" :
45
+ cnt += 1
46
+ sink (r , c ) ## Sink the entire island by converting all connected "1"s to "0"s.
47
+ return cnt
48
+
49
+ mySolution = Solution ()
50
+ mySolution .numIslands (
51
+ [
52
+ ["1" ,"1" ,"1" ,"1" ,"0" ],
53
+ ["1" ,"1" ,"0" ,"1" ,"0" ],
54
+ ["1" ,"1" ,"0" ,"0" ,"0" ],
55
+ ["0" ,"0" ,"0" ,"0" ,"0" ]
56
+ ]
57
+ )
58
+
59
+
60
+
You can’t perform that action at this time.
0 commit comments