| 
 | 1 | +from typing import List  | 
 | 2 | + | 
 | 3 | + | 
 | 4 | +class Solution:  | 
 | 5 | + def numIslands(self, grid: List[List[str]]) -> int:  | 
 | 6 | + count = 0  | 
 | 7 | + for i in range(0, len(grid)):  | 
 | 8 | + for j in range(0, len(grid[i])):  | 
 | 9 | + if grid[i][j] == "1":  | 
 | 10 | + count += 1  | 
 | 11 | + self.checkIslandDFS(grid, i, j)  | 
 | 12 | + return count  | 
 | 13 | + | 
 | 14 | + def checkIslandDFS(self, grid, i, j):  | 
 | 15 | + # base case  | 
 | 16 | + if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[i]) or grid[i][j] == "0":  | 
 | 17 | + return  | 
 | 18 | + | 
 | 19 | + grid[i][j] = "0"  | 
 | 20 | + # check all adjacents  | 
 | 21 | + self.checkIslandDFS(grid, i, j-1) # left  | 
 | 22 | + self.checkIslandDFS(grid, i, j+1) # right  | 
 | 23 | + self.checkIslandDFS(grid, i-1, j) # top  | 
 | 24 | + self.checkIslandDFS(grid, i+1, j) # bottom  | 
 | 25 | + | 
 | 26 | + | 
 | 27 | +sol = Solution()  | 
 | 28 | +# grid = [  | 
 | 29 | +# ["1", "1", "1", "1", "0"],  | 
 | 30 | +# ["1", "1", "0", "1", "0"],  | 
 | 31 | +# ["1", "1", "0", "0", "0"],  | 
 | 32 | +# ["0", "0", "0", "0", "0"]  | 
 | 33 | +# ]  | 
 | 34 | +# print(sol.numIslands(grid))  | 
 | 35 | + | 
 | 36 | +# grid = [  | 
 | 37 | +# ["1", "1", "0", "0", "0"],  | 
 | 38 | +# ["1", "1", "0", "0", "0"],  | 
 | 39 | +# ["0", "0", "1", "0", "0"],  | 
 | 40 | +# ["0", "0", "0", "1", "1"]  | 
 | 41 | +# ]  | 
 | 42 | +grid = [["1", "1", "1"], ["0", "1", "0"], ["1", "1", "1"]]  | 
 | 43 | +print(sol.numIslands(grid))  | 
0 commit comments