Number of Islands
Medium Graphs AI round
grid is a map of m rows and n columns. Each cell holds the character '1' for land or '0' for water.
Land cells that share a side, one above, below, left or right of the other, belong to the same island. Cells that meet only at a corner do not, and everything beyond the edge of the map is water.
Return the number of islands in grid.
Example 1
Input: grid = [["1","1","0","0","1","1"],["1","0","0","0","0","1"],["0","0","0","1","0","0"],["0","1","1","1","0","0"],["0","0","0","0","0","1"]]
Output: 4
Four islands: three land cells in the top left corner, three in the top right corner, four in the middle that join by their sides, and one cell alone at the bottom right.
Example 2
Input: grid = [["1","0","1"],["0","1","0"],["1","0","1"]]
Output: 5
Example 3
Input: grid = [["1","1","1"],["1","0","1"],["1","1","1"]]
Output: 1
Constraints
1 ≤ m, n ≤ 1000m · n ≤ 10⁵- Every row of
gridhasncells grid[i][j]is'0'or'1'
Practice this in an AI round
30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.
Your first AI round is free.
Watch the explanation
More Graphs
- Rotting OrangesAI round · Medium
- Word LadderAI round · Hard
- Graph Valid TreeMedium
- Walls and GatesMedium
- Number of Connected Components in an Undirected GraphMedium