1+ import unittest
2+
3+
14class Solution (object ):
25 def numIslands (self , grid ):
36 """
@@ -9,19 +12,68 @@ def numIslands(self, grid):
912 return 0
1013 islands = 0
1114 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
1316 if grid [i ][j ] == '1' :
1417 self .explore (grid , i , j )
1518 islands += 1
1619 return islands
1720
1821 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
2024 if i - 1 >= 0 and grid [i - 1 ][j ] == '1' :
2125 self .explore (grid , i - 1 , j )
2226 if j - 1 >= 0 and grid [i ][j - 1 ] == '1' :
2327 self .explore (grid , i , j - 1 )
2428 if i + 1 < len (grid ) and grid [i + 1 ][j ] == '1' :
2529 self .explore (grid , i + 1 , j )
2630 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