Count Islands
grid is a list of rows of 1 (land) and 0 (water). Cells connect horizontally and vertically. Return the number of islands (connected groups of land).
Requirements
- Visit each cell at most once ().
Examples
EXAMPLE WALKTHROUGHthree islands
A guided view of the published example, not a trace of your code.
INPUT
[[[1,1,0,0],[1,1,0,0],[0,0,1,0],[0,0,0,1]]]TASKcount_islands()
EXPECTED OUTPUT
3Start with the input values shown in this example.
Example 1 of 3
Input: grid = [[1,1,0,0],[1,1,0,0],[0,0,1,0],[0,0,0,1]]
Output: 3
Explanation: three islands
Input: grid = [[1,1,1],[0,1,0],[1,1,1]]
Output: 1
Explanation: one connected island
Input: grid = [[0,0],[0,0]]
Output: 0
Explanation: all water
Hint 1
Scan the grid; when you find unvisited land, flood-fill its island with BFS or DFS and count one.