1
+ import unittest
2
+
3
+
1
4
class Solution (object ):
2
5
def numIslands (self , grid ):
3
6
"""
@@ -9,19 +12,68 @@ def numIslands(self, grid):
9
12
return 0
10
13
islands = 0
11
14
for i in range (len (grid )):
12
- for j in range (len (grid [i ])):
15
+ for j in range (len (grid [i ])): # explore each row, each col
13
16
if grid [i ][j ] == '1' :
14
17
self .explore (grid , i , j )
15
18
islands += 1
16
19
return islands
17
20
18
21
def explore (self , grid , i , j ):
19
- grid [i ][j ] = 'X'
22
+ grid [i ][j ] = 'X' # make explored as 'X', then won't be explore by '1' again
23
+ # recursively explore all the neighbors
20
24
if i - 1 >= 0 and grid [i - 1 ][j ] == '1' :
21
25
self .explore (grid , i - 1 , j )
22
26
if j - 1 >= 0 and grid [i ][j - 1 ] == '1' :
23
27
self .explore (grid , i , j - 1 )
24
28
if i + 1 < len (grid ) and grid [i + 1 ][j ] == '1' :
25
29
self .explore (grid , i + 1 , j )
26
30
if j + 1 < len (grid [i ]) and grid [i ][j + 1 ] == '1' :
27
- self .explore (grid , i , j + 1 )
31
+ self .explore (grid , i , j + 1 )
32
+
33
+
34
+ class SolutionDFS (object ):
35
+ def numIslands (self , grid ):
36
+ """
37
+ :type grid: List[List[str]]
38
+ :rtype: int
39
+ """
40
+ # DFS with marks
41
+ if grid is None or len (grid ) == 0 :
42
+ return 0
43
+ islands = 0
44
+ self .visited = set ()
45
+ self .rows , self .cols = len (grid ), len (grid [0 ])
46
+ for r in range (self .rows ):
47
+ for c in range (self .cols ):
48
+ if grid [r ][c ] == "1" and (r , c ) not in self .visited :
49
+ self .explore (r , c , grid )
50
+ islands += 1
51
+ return islands
52
+
53
+ def explore (self , r , c , grid ):
54
+ if r not in range (self .rows ) or c not in range (self .cols ) or grid [r ][c ] == "0" or (r , c ) in self .visited :
55
+ return
56
+ self .visited .add ((r , c ))
57
+ directions = [(0 , 1 ), (0 , - 1 ), (1 , 0 ), (- 1 , 0 )]
58
+ for dr , dc in directions : # explore all the neighbors
59
+ self .explore (r + dr , c + dc , grid )
60
+
61
+
62
+ class Test (unittest .TestCase ):
63
+ grid = [["1" , "1" , "0" , "0" , "0" ],
64
+ ["1" , "1" , "0" , "0" , "0" ],
65
+ ["0" , "0" , "1" , "0" , "0" ],
66
+ ["0" , "0" , "0" , "1" , "1" ]]
67
+ expected = 3
68
+ test_funcs1 = [Solution ().numIslands ]
69
+ test_funcs2 = [SolutionDFS ().numIslands ]
70
+ test_funcs = test_funcs1 + test_funcs2
71
+
72
+ def testNum (self ):
73
+ for test_func in self .test_funcs :
74
+ self .assertEqual (test_func (self .grid ), self .expected )
75
+ # restore input
76
+ self .grid = [["1" , "1" , "0" , "0" , "0" ],
77
+ ["1" , "1" , "0" , "0" , "0" ],
78
+ ["0" , "0" , "1" , "0" , "0" ],
79
+ ["0" , "0" , "0" , "1" , "1" ]]
0 commit comments