Number of islands

Graphs Traversal Problems Medium

Given a grid of size N x M (N is the number of rows and M is the number of columns in the grid) consisting of '0's (Water) and ‘1's(Land). Find the number of islands.

Examples:


Input: grid = [ ["1", "1", "1", "0", "1"], ["1", "0", "0", "0", "0"], ["1", "1", "1", "0", "1"], ["0", "0", "0", "1", "1"] ]

Output: 2

Explanation: This grid contains 2 islands. Each '1' represents a piece of land, and the islands are formed by connecting adjacent lands horizontally or vertically. Despite some islands having a common edge, they are considered separate islands because there is no land connectivity in any of the eight directions between them. Therefore, the grid contains 2 islands.

Input: grid = [ ["1", "0", "0", "0", "1"], ["0", "1", "0", "1", "0"], ["0", "0", "1", "0", "0"], ["0", "1", "0", "1"," 0"] ]

Output: 1

Explanation: In the given grid, there's only one island as all the '1's are connected either horizontally, vertically, or diagonally, forming a single contiguous landmass surrounded by water on all sides.

Input: grid = [ ["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"] ]

Constraints

·  N == grid.length

·  M == grid[i].length

·  1 <= N, M <= 300

·  grid[i][j] is '0' or '1'.

Hints

  • "DFS (Recursive or Stack-based Iterative): Start from an unvisited '1', mark all reachable '1's as visited using DFS. Each DFS call marks an entire island. BFS (Queue-based): Similar to DFS, but uses a queue to explore all connected lands level by level."
  • "Treat each '1' as an initially separate set. Merge adjacent '1' cells into one connected component using Union-Find. The number of unique components after merging gives the number of islands."

Company Tags

Seagate Technology DoorDash Flipkart Goldman Sachs American Express Databricks Pinterest Visa Philips Healthcare HashiCorp Electronic Arts Western Digital Wayfair Dropbox Robinhood Broadcom Uber Shopify Target Intel McKinsey & Company Optum Splunk AMD Qualcomm Google Microsoft Amazon Meta Apple Netflix Adobe