Number of Islands
Medium Graphs
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'
Solve it here
Write it in Python, Java or C++, run it on your own cases, and submit against hidden tests.
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.
See the AI roundWatch the explanation
More Graphs
- Rotting OrangesAI round · Medium
- Word LadderAI round · Hard
- Is Graph Bipartite?AI round · Medium
- Graph Valid TreeMedium
- Walls and GatesMedium