-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.py
28 lines (25 loc) · 987 Bytes
/
solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
stack = []
count = 0
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
if grid[i][j] == '1':
count += 1
stack.append((i, j))
while len(stack) > 0:
x, y = stack.pop()
grid[x][y] = '-1'
if x > 0 and grid[x - 1][y] == '1':
stack.append((x - 1, y))
if x < len(grid) - 1 and grid[x + 1][y] == '1':
stack.append((x + 1, y))
if y > 0 and grid[x][y - 1] == '1':
stack.append((x, y - 1))
if y < len(grid[0]) - 1 and grid[x][y + 1] == '1':
stack.append((x, y + 1))
return count