# 200_岛屿数量


"""

11110
11010
11000
00000

11000
11000
00100
00011

"""

directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]

def numIslands1(grid):
m = len(grid)
n = len(grid[0])
if m == 0:
return 0

marked = [[False for _ in range(n)] for _ in range(m)]
count = 0
for i in range(m):
for j in range(n):
if not marked[i][j] and grid[i][j] == '1':
count += 1
dfs(grid, i, j, m, n, marked)
return count

def dfs(grid, i, j, m, n, marked):
marked[i][j] = True
for direction in directions:
new_i = i + direction[0]
new_j = j + direction[1]
if 0 <= new_i < m and 0 <= new_j < n and not marked[new_i][new_j] and grid[new_i][new_j] == '1':
dfs(grid, new_i, new_j, m, n, marked)

# 方法二
def flag_islands(i, j, grid, flag):
# 上
if i - 1 >=0 and grid[i-1][j] == '1':
grid[i-1][j] = flag
flag_islands(i-1, j, grid, flag)

# 下
if i+1 < len(grid) and grid[i+1][j] == '1':
grid[i+1][j] = flag
flag_islands(i+1, j, grid, flag)

# 左
if j - 1 >= 0 and grid[i][j-1] == '1':
grid[i][j-1] = flag
flag_islands(i, j-1, grid, flag)

# 右
if j + 1 < len(grid[i]) and grid[i][j+1] == '1':
grid[i][j+1] = flag
flag_islands(i, j+1, grid, flag)

def numIslands2(grid):
if not grid:
return 0
result = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] != '1':
continue
flag_islands(i, j, grid, result)
result += 1
return result


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

Lishu_cc

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-23

09-02 161
01-20 224
09-12 454
06-20 211
11-08 5958
04-06 137
07-27 337