Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 53bb263

Browse files
200: Number of Islands
1 parent ba0eaca commit 53bb263

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

python/number_of_islands.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# https://leetcode.com/problems/number-of-islands/description/
2+
# T: O(MN) where M is the number of rows and N is the number of columns.
3+
# S: O(MN) where M is the number of rows and N is the number of columns.
4+
5+
def numIslands(self, grid):
6+
if not grid:
7+
return 0
8+
9+
count = 0
10+
for i in range(len(grid)):
11+
for j in range(len(grid[0])):
12+
if grid[i][j] == '1':
13+
self.dfs(grid, i, j)
14+
count += 1
15+
return count
16+
17+
def dfs(self, grid, i, j):
18+
if i<0 or j<0 or i>=len(grid) or j>=len(grid[0]) or grid[i][j] != '1':
19+
return
20+
grid[i][j] = '#'
21+
self.dfs(grid, i+1, j)
22+
self.dfs(grid, i-1, j)
23+
self.dfs(grid, i, j+1)
24+
self.dfs(grid, i, j-1)

0 commit comments

Comments
 (0)