MEDIUM NC#80 Blind #30 Graphs / DFS
200. Number of Islands
📖 Problem
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are surrounded by water.
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •Recursive stack flow
- •Cycle prevention
- •Post-order reasoning
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply DFS reasoning pattern
- •Apply Recursion reasoning pattern
💡 Approach
- → Use DFS to mark all connected land as visited
- → Iterate through grid, start DFS when finding unvisited land
- → Count number of DFS calls (islands)
- → Mark visited by changing '1' to '0' in place
- → Time: O(m * n), Space: O(m * n) worst case for recursion
🧭 Prerequisites
🛠️ Hints & Pitfalls
Hints
- •Use DFS to mark all connected land as visited
- •Iterate through grid, start DFS when finding unvisited land
- •Count number of DFS calls (islands)
Common Pitfalls
- •Mark visited by changing '1' to '0' in place
- •Time: O(m * n), Space: O(m * n) worst case for recursion
🧪 Test Cases
Hidden tests on submit: 3
Test Case 1
Not run Input:
dfs(r: number, c: number); Expected:
Computed from hidden reference Test Case 2
Not run Input:
dfs(r + 1, c); Expected:
Computed from hidden reference Test Case 3
Not run Input:
dfs(r - 1, c); Expected:
Computed from hidden reference 📝 Code Editor
📤 Output