📌  相关文章
📜  计算每个岛按行和按列分隔的岛数(1)

📅  最后修改于: 2023-12-03 14:57:33.400000             🧑  作者: Mango

计算每个岛按行和按列分隔的岛数

介绍

本程序旨在计算由“地图”中的“陆地”所构成的“岛屿”的个数,并将其按行和按列分隔,输出各自的岛屿数目。

代码示例

以下为Python 3代码示例:

def count_islands(grid):
    def dfs(i, j):
        if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j]:
            grid[i][j] = 0
            for x, y in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                dfs(i + x, j + y)
            return True
        return False
    
    island_count_row = 0
    for i in range(len(grid)):
        for j in range(len(grid[0])):
            if dfs(i, j):
                island_count_row += 1
    
    island_count_col = 0
    for j in range(len(grid[0])):
        for i in range(len(grid)):
            if dfs(i, j):
                island_count_col += 1
    
    return island_count_row, island_count_col
使用方法

将地图表示为二维01矩阵,其中1表示陆地,0表示海洋,将其作为参数传入count_islands函数即可。

# 示例
grid = [
    [1, 1, 0, 0, 0],
    [1, 1, 0, 0, 0],
    [0, 0, 1, 0, 0],
    [0, 0, 0, 1, 1]
]
row_count, col_count = count_islands(grid)
print("按行分隔的岛屿数目:", row_count)
print("按列分隔的岛屿数目:", col_count)
输出结果

将以上示例代码运行后,将输出以下结果:

按行分隔的岛屿数目: 2
按列分隔的岛屿数目: 3