Uber · Question 34 · Graphs
Number of Islands
Problem
Given a 2D grid of ‘1’s (land) and ‘0’s (water), count the number of islands (connected components of land).
Approach
Use BFS (or DFS) to traverse connected lands. Mark visited cells to avoid recounting. (BFS)
Time O(m*n)Space O(m*n)
How it works
- 1Scan every cell; each fresh '1' starts an island.
- 2BFS floods the whole island, sinking cells to '0'.
- 3Count one per flood; sunk cells never recount.
Sample input / output
Input: 4 5 11000 11000 00100 00011 Output: 3
Constraints
1 <= m, n <= 300; cells are '0' (water) or '1' (land).
Solution — read it, then walk it
Time O(m*n)Space O(m*n)Loops 5Branches 5Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/33
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