• API
• FAQ
• Tools
• Archive
SHARE
TWEET

# Untitled

a guest Sep 15th, 2019 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. class Solution:
2.     def numIslands(self, grid: List[List[str]]) -> int:
3.         if not grid or not grid[0]: return 0
4.         visited = [[False] * len(grid[0]) for _ in range(len(grid))]
5.         res = 0
6.
7.         for i in range(len(grid)):
8.             for j in range(len(grid[0])):
9.                 if grid[i][j] == '1' and not visited[i][j]:
10.                     res += 1
11.                     self.dfs(grid, visited, i, j)
12.         return res
13.
14.     def dfs(self, grid: List[List[str]], visited: List[List[bool]], i: int, j: int) -> None:
15.         if i >= 0 and j >= 0 and i < len(grid) and j < len(grid[0]) and not visited[i][j] and grid[i][j] == '1':
16.             visited[i][j] = True
17.             self.dfs(grid, visited, i + 1, j)
18.             self.dfs(grid, visited, i - 1, j)
19.             self.dfs(grid, visited, i, j + 1)
20.             self.dfs(grid, visited, i, j - 1)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top