Number of Islands

medium · graph, dfs, bfs, grid

Number of Islands

Given a grid of characters grid consisting of '1' (land) and '0' (water), return the number of islands. An island is formed by connecting adjacent lands horizontally or vertically.

The grid is provided as a slice of equal-length strings.

Function signature

func NumIslands(grid []string) int

Example

grid = [
  "11110",
  "11010",
  "11000",
  "00000"
]
output = 1

Constraints

  • 0 <= len(grid) <= 200
  • 0 <= len(grid[i]) <= 200
  • grid is rectangular

Notes

  • Use DFS/BFS and a visited set to count components.
Run tests to see results
No issues detected