問題
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
例
入力:
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.
入力:
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.
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
上下左右でつながっている land cell は、1つの island に属します。
ヒント 2
新しい land を見つけたら、同じ領域を flood-fill して二重に数えないようにします。
ヒント 3
再帰探索中は、grid の境界を丁寧に確認してください。
目安の計算量
時間 O(rows × columns)、追加メモリ O(rows × columns)
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。