File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ 200. Number of Islands
3+ https://leetcode.com/problems/number-of-islands/
4+
5+ Solution:
6+ To solve this problem, we can use a depth-first search (DFS) to explore all connected land cells.
7+ We can create a helper function that takes the current cell and marks it as visited.
8+
9+ - We can iterate through all cells in the grid.
10+ - If the current cell is land, we explore all connected land cells using DFS.
11+ - We mark all connected land cells as visited.
12+ - We increment the island count by 1.
13+
14+ Time complexity: O(m x n)
15+ - m and n are the dimensions of the grid.
16+ - We explore all cells in the grid once.
17+
18+ Space complexity: O(m x n)
19+ - We use a recursive call stack to explore all connected land cells.
20+ - The maximum depth of the call stack is the number of cells in the grid.
21+
22+ """
23+
24+ from typing import List
25+
26+ class Solution :
27+ def numIslands (self , grid : List [List [str ]]) -> int :
28+ if not grid :
29+ return 0
30+
31+ m , n = len (grid ), len (grid [0 ])
32+
33+ island_count = 0
34+
35+ def dfs (i , j ):
36+ if i < 0 or i >= m or j < 0 or j >= n or grid [i ][j ] != '1' :
37+ return
38+ grid [i ][j ] = '#'
39+
40+ dfs (i - 1 , j )
41+ dfs (i + 1 , j )
42+ dfs (i , j - 1 )
43+ dfs (i , j + 1 )
44+
45+ for i in range (m ):
46+ for j in range (n ):
47+
48+ if grid [i ][j ] == '1' :
49+ dfs (i , j )
50+ island_count += 1
51+
52+ return island_count
53+
54+
You can’t perform that action at this time.
0 commit comments