← All problemsExample 1 Example 2
Problem
Number of Islands
Medium- graphs
- bfs
- dfs
- matrix
grid is a rectangle of strings, written as an array of rows. Each cell is "1" for land or "0" for water. An island is a group of land cells joined by steps up, down, left or right. Cells that touch only at a corner are not joined. Return how many islands the grid has.
- Input
grid = [["1", "1", "0"], ["0", "1", "0"], ["0", "0", "1"]]- Output
2- Explanation
the three land cells in the top-left form one island. The land cell in the bottom-right touches it only diagonally, so it is a second island.
- Input
grid = [["0", "0"], ["0", "0"]]- Output
0- Explanation
there is no land, so there are no islands.
Constraints:
1 <= grid.length <= 501 <= grid[i].length <= 50, and every row has the same length- each cell is the string
"0"or the string"1"
JavaScript
Tab indents. Press Esc, then Tab to leave the editor.
Ctrl or ⌘ + Enter runs the tests.
Run your code to see every test here. Nothing is submitted or recorded.