Approach
To effectively answer the question “How do you calculate the number of islands in a 2D grid?”, follow this structured framework:
Understand the Problem: Define what constitutes an island.
Choose an Algorithm: Identify suitable algorithms for grid traversal.
Implement the Solution: Write and explain the code.
Analyze Complexity: Discuss time and space complexities.
Provide Edge Cases: Mention any special scenarios to consider.
Key Points
Definition of an Island: An island is formed by connecting adjacent lands (1s) horizontally or vertically surrounded by water (0s).
Traversal Methods: Depth First Search (DFS) or Breadth First Search (BFS) are commonly used to explore the grid.
Iterative vs. Recursive: Understand the trade-offs between using an iterative approach and recursion.
Complexity Analysis: Clearly articulate the efficiency of your solution.
Edge Cases: Consider grids with no land, all land, or varying dimensions.
Standard Response
To calculate the number of islands in a 2D grid, you can use the Depth First Search (DFS) algorithm. Here’s how you can approach the problem step-by-step:
Initialize the Grid: Represent the grid as a 2D array where '1' indicates land and '0' indicates water.
Count Islands:
Create a variable to keep track of the number of islands.
Loop through each cell in the grid.
If a cell contains '1', increment your island count and perform DFS from that cell to mark all connected lands.
DFS Implementation:
In your DFS function, change the current cell from '1' to '0' to mark it as visited.
Recursively call DFS for all four directions (up, down, left, right).
Here's a sample code implementation in Python:
Complexity Analysis
Time Complexity: O(M * N), where M is the number of rows and N is the number of columns in the grid. Each cell is visited once.
Space Complexity: O(M * N) in the worst case due to the recursion stack in DFS.
Tips & Variations
Common Mistakes to Avoid
Ignoring Diagonal Connections: Only consider horizontal and vertical connections when defining islands.
Not Marking Visited Cells: Failing to mark cells as visited can lead to counting the same island multiple times.
Misunderstanding Input: Ensure you understand whether the grid can be empty or consists solely of water or land.
Alternative Ways to Answer
Using BFS: Instead of DFS, you can use a queue to implement a BFS approach, which iteratively explores the grid.