DFS on grid
Last updated: March 31, 2026
Quick Overview
Implement a Depth-First Search (DFS) algorithm to traverse a 2D grid, where each cell can either be land (1) or water (0). Your task is to count the number of distinct islands formed by connected land cells, where connectivity is defined as horizontal or vertical adjacency. The function should take a 2D grid as input and return an integer representing the number of islands.
Square/Block
March 31, 2026128
12
1,853 solved
Implement a Depth-First Search (DFS) algorithm to traverse a 2D grid, where each cell can either be land (1) or water (0). Your task is to count the number of distinct islands formed by connected land cells, where connectivity is defined as horizontal or vertical adjacency. The function should take a 2D grid as input and return an integer representing the number of islands.
Coding interviews at Square/Block focus on problem-solving approach as much as the final solution. The interviewer wants to see you break down the problem, consider edge cases, and optimize iteratively. Communication throughout the process is key.
What the Interviewer Expects
- Recognize the underlying problem pattern (sliding window, two pointers, BFS/DFS, etc.)
- Discuss multiple approaches and trade-offs before coding
- Implement an optimal solution with clean, production-quality code
- Handle all edge cases including boundary conditions and invalid input
- Optimize both time and space complexity with clear justification
- Test your solution systematically with well-chosen examples
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you modify your solution to handle streaming input?
- How would you test this solution thoroughly?
- How would your solution change if the input was sorted?
- What is the worst-case input for your solution?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Problem Analysis
The problem revolves around counting distinct islands in a 2D grid, where each island consists of connected land cells (1s). The connectivity is defined by horizontal and vertical adjacency, making th...
Approach
- Initialization: Start by checking if the grid is empty. If it is, return 0 since there are no islands.
- Grid Traversal: Iterate through each cell in the grid. For each cell:
- If the c...