问题描述,其实就是找出图中互不相连的岛屿数量
Leetcode代码
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
m = len(grid)
n = len(grid[0])
directions = [(+1, 0), (-1, 0), (0, +1), (0, -1)]
isoland_unchecked = set()
isoland_count = 0
for x in range(m):
for y in range(n):
if grid[x][y] == '1':
isoland_unchecked.add((x, y))
while isoland_unchecked:
ix, iy = isoland_unchecked.pop()
grid[ix][iy] = '0'
for dx, dy in directions:
if 0 <= ix + dx < m and 0 <= iy + dy < n and grid[ix + dx][iy + dy] == '1':
isoland_unchecked.add((ix + dx, iy + dy))
isoland_count += 1
return isoland_count
LeetCode提交结果
Pycharm代码
class Solution:
def numIslands(self, grid):
m = len(grid)
n = len(grid[0])
directions = [(+1, 0), (-1, 0), (0, +1), (0, -1)]
isoland_unchecked = set()
isoland_count = 0
for x in range(m):
for y in range(n):
if grid[x][y] == '1':
isoland_unchecked.add((x, y))
while isoland_unchecked:
ix, iy = isoland_unchecked.pop()
grid[ix][iy] = '0'
for dx, dy in directions:
if 0 <= ix + dx < m and 0 <= iy + dy < n and grid[ix + dx][iy + dy] == '1':
isoland_unchecked.add((ix + dx, iy + dy))
isoland_count += 1
return isoland_count
grid = [
["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]
]
print(Solution().numIslands(grid))
grid = [
["1", "1", "0", "0", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "1", "0", "0"],
["0", "0", "0", "1", "1"]
]
print(Solution().numIslands(grid))