Google · Question 63 · Graphs
Number of Islands (DFS)
Problem
Count the number of islands ( connected groups of '1's) in a 2D grid using DFS.
Approach
Perform DFS to mark connected land as visited.
Time O(rows*cols)Space O(rows*cols)
How it works
- 1Traverse the grid and call DFS on unvisited land.
- 2DFS visits and marks all connected land cells.
- 3Increment the island count per DFS call.
- 4Return the total islands.
Sample input / output
Input: 4 5 11000 11000 00100 00011 Output: 3
Constraints
m == grid.length; n == grid[i].length; 1 <= m, n <= 300; cells are '0' or '1'.
Solution — read it, then walk it
Time O(rows*cols)Space O(rows*cols)Loops 2Branches 4Returns 3source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/31
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits