DFS on grid
Last updated: March 5, 2026
Quick Overview
Implement a depth-first search (DFS) algorithm to traverse a 2D grid represented by a matrix of integers, 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 being adjacent horizontally or vertically. The function should return an integer representing the total number of islands found in the grid.
Amazon
March 5, 202627
7
214 solved
Implement a depth-first search (DFS) algorithm to traverse a 2D grid represented by a matrix of integers, 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 being adjacent horizontally or vertically. The function should return an integer representing the total number of islands found in the grid.
Coding interviews at Amazon 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
- 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
- Can you solve this in a single pass?
- What if the input doesn't fit in memory?
- How would you modify your solution to handle streaming input?
- Can you optimize the space complexity of 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
In this problem, we are tasked with counting distinct islands in a 2D grid where land is represented by 1s and water by 0s. The optimal approach to this problem is to use Depth-First Search (DFS) due ...
Approach
- Initialize a counter for the number of islands and a set to track visited cells.
- Loop through each cell in the grid:
- If the cell is land (1) and not visited, increment the island counter....