中級 0件解決済み 正答率0%

Count Islands

Count groups of connected land cells in a grid.

問題

The grid holds 1 for land and 0 for water. Land cells that touch up, down, left or right belong to the same island. Count the islands; a recursive flood fill is a natural approach.

Implement count_islands(grid).

Input

grid: A rectangular grid of 0s and 1s.

Output

Return the number of islands.

制約

0 ≤ rows, columns ≤ 100

例

例 1
入力:
grid = [
    [1, 1, 0, 0],
    [0, 1, 0, 1],
    [0, 0, 0, 1]
]

期待される出力:
expected = 2
入力:
std::vector<std::vector<long long>> grid = {
    {1, 1, 0, 0},
    {0, 1, 0, 1},
    {0, 0, 0, 1}
};

期待される出力:
long long expected = 2;
入力:
long[][] grid = new long[][] {
    new long[] {1, 1, 0, 0},
    new long[] {0, 1, 0, 1},
    new long[] {0, 0, 0, 1}
};

期待される出力:
long expected = 2;

解説

The top-left group of 3 cells is one island; the two 1s on the right form a second: 2.

例 2
入力:
grid = [
    [1, 0, 1],
    [0, 1, 0]
]

期待される出力:
expected = 3
入力:
std::vector<std::vector<long long>> grid = {
    {1, 0, 1},
    {0, 1, 0}
};

期待される出力:
long long expected = 3;
入力:
long[][] grid = new long[][] {
    new long[] {1, 0, 1},
    new long[] {0, 1, 0}
};

期待される出力:
long expected = 3;

解説

Diagonal neighbors don't connect, so each 1 is its own island: 3.

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。