DFS on grid
Last updated: January 12, 2026
Quick Overview
Given a 2D grid of 0s and 1s, where 1s represent land and 0s represent water, implement a Depth-First Search (DFS) algorithm to find the number of distinct islands in the grid. An island is formed by connecting adjacent lands horizontally or vertically. Your function should return the total count of islands found in the grid.
Slack
January 12, 202671
13
1,685 solved
Given a 2D grid of 0s and 1s, where 1s represent land and 0s represent water, implement a Depth-First Search (DFS) algorithm to find the number of distinct islands in the grid. An island is formed by connecting adjacent lands horizontally or vertically. Your function should return the total count of islands found in the grid.
Slack uses this problem in the Take-home Project to evaluate your algorithmic thinking. They expect you to discuss multiple approaches, analyze trade-offs between them, and implement the optimal solution with clean, readable code.
What the Interviewer Expects
- Quickly identify the optimal approach and its theoretical basis
- Handle complex algorithm design with multiple interacting components
- Write concise, elegant code under time pressure
- Prove correctness of your approach and discuss alternative solutions
- Optimize beyond the obvious: discuss constant factor improvements
- Address follow-up variations and explain how the solution generalizes
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
- What is the worst-case input for your solution?
- What if the input doesn't fit in memory?
- Can you solve this iteratively instead of recursively (or vice versa)?
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
In this problem, we are tasked with counting distinct islands in a 2D grid represented by 1s (land) and 0s (water). The key pattern here is the Depth-First Search (DFS). This approach is suitable ...
Approach
The algorithm will follow these steps:
- Initialize a counter to keep track of the number of islands.
- Loop through each cell in the grid. If we find a '1', increment the island counter and initiat...