Two classics show up in almost every interview loop: Number of Islands and Course Schedule. They look different, but both are graphs. A grid is a graph of cells; prerequisites are a graph of tasks. With the BFS and DFS you know, plus two small tricks, you can solve both families.
The 12 interview patterns: you are here
- 1Two Pointerssorted + pair
- 2Sliding Windowcontiguous subarray
- 3Prefix Sum + Hash Maprange sums, sum = K
- 4Binary Search on Answersmallest value that works
- 5Fast & Slow Pointerscycle, middle
- 6Merge Intervalsoverlapping ranges
- 7Monotonic Stacknext greater element
- 8Heap / Top-Ktop K, Kth largest
- 9Tree Patternsdepth, paths, levels
- 10Grid BFS & Topological Sortislands, dependencies
- 11Backtrackingall combinations
- 12DP Patternscount ways, min cost
Part 1: grids are graphs
Each cell is a node connected to its 4 neighbours. To count islands, scan the map; each time you step on land you've never seen, you've found a new island, so flood it (mark every connected land cell as seen). Paint your own map:
🏝️ Paint the map, then count the islands
Tap cells to switch land and water. Diagonal cells don't join islands.
Scan every cell. When you hit land you haven't seen, that's a new island: flood-fill it (BFS or DFS to its 4 neighbours) so you never count it twice. Each cell is visited once: O(rows × cols).
Part 2: topological sort (order with prerequisites)
You can't wear shoes before socks, and you can't take System Design before DSA. Topological sort finds an order that respects every “A before B” rule. Step through a semester plan:
🎓 Plan your semesters: topological sort
needs nothing
needs nothing
needs Maths 1, Programming
needs Programming
needs DSA
needs DSA, DBMS
Start with every course that needs nothing: Maths 1, Programming.
Each course keeps a count of prerequisites still pending. Take any course whose count is 0, then lower the count of everything that needed it. If you ever get stuck with courses left, there's a cycle: the plan is impossible.
🔍 Use grid BFS / topological sort when you see
- ✓A 2D grid: islands, regions, “connected”, flood fill
- ✓Fewest steps or minutes on a grid or graph (BFS)
- ✓Prerequisites, dependencies, build or task order
- ✓“Can all tasks be finished?” (cycle check)
🚫 Don't use it when
- ✗A tree with no cycles (simpler tree DFS/BFS)
- ✗Weighted shortest paths (needs Dijkstra)
- ✗All combinations or arrangements (backtracking)
The templates
# Islands: scan, and flood every new land cell
for each cell (r, c):
if land and not seen:
count += 1
BFS from (r, c) to 4 neighbours, marking seen
# Topological sort (Kahn)
pending[x] = number of prerequisites of x
queue = all x with pending[x] == 0
while queue:
x = queue.pop(); order.append(x)
for y that needs x:
pending[y] -= 1
if pending[y] == 0: queue.append(y)
cycle if len(order) < number of tasks⚡ Memory tricks
- 1
“New land = new island, flood it”
Count, then mark the whole island as seen.
- 2
“BFS rings = fewest steps”
Use BFS whenever the question says minimum steps or minutes.
- 3
“Socks before shoes”
Topological sort: everything after what it depends on.
- 4
“Zero pending goes first; stuck means cycle”
Kahn's algorithm in one line.
Code: number of islands and course order
Outputs in the comments come from running the code, including the impossible case with a cycle.
from collections import deque
def count_islands(grid):
"""Each time we find new land, flood-fill (BFS) the whole island and count it."""
rows, cols = len(grid), len(grid[0])
seen = set()
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == "1" and (r, c) not in seen:
islands += 1
queue = deque([(r, c)])
seen.add((r, c))
while queue:
x, y = queue.popleft()
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): # 4 neighbours
nx, ny = x + dx, y + dy
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == "1" and (nx, ny) not in seen:
seen.add((nx, ny))
queue.append((nx, ny))
return islands
def course_order(n, prereqs):
"""Topological sort (Kahn): take courses with no pending prerequisites first."""
after = [[] for _ in range(n)]
pending = [0] * n # prerequisites still not done
for course, before in prereqs:
after[before].append(course)
pending[course] += 1
ready = deque(c for c in range(n) if pending[c] == 0)
order = []
while ready:
c = ready.popleft()
order.append(c)
for nxt in after[c]:
pending[nxt] -= 1
if pending[nxt] == 0:
ready.append(nxt)
return order if len(order) == n else [] # [] means a cycle: impossible
grid = ["11000",
"11000",
"00100",
"00011"]
print(count_islands(grid)) # 3
print(course_order(4, [[1, 0], [2, 0], [3, 1], [3, 2]])) # [0, 1, 2, 3]
print(course_order(2, [[0, 1], [1, 0]])) # [] (a cycle)One pattern, many problems
| Famous problem | How the pattern solves it | Level |
|---|---|---|
| Number of Islands | Scan + flood fill | Medium |
| Flood Fill | BFS/DFS from one cell | Easy |
| Max Area of Island | Flood fill, count cells per island | Medium |
| Rotting Oranges | Multi-source BFS, one ring per minute | Medium |
| Shortest Path in Binary Matrix | BFS with 8 neighbours | Medium |
| Course Schedule I & II | Kahn's algorithm (topological sort) | Medium |
| Clone Graph | BFS/DFS with a map old → new | Medium |
| Alien Dictionary | Build letter order edges, then topological sort | Hard |
🎯 Spot the pattern: is it grid BFS / topological sort?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. Count connected groups of 1s in a grid.
2. Given prerequisites, can you finish all courses?
3. Find the minimum steps for a knight to reach a square on a chessboard.
4. Generate all subsets of a set.
5. Find the build order for packages that depend on each other.
🧠 PATH memory card
Remember grid BFS and topological sort for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
Getting dressed in order: innerwear, trousers, socks, then shoes. Shoes can't come before socks.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Flood new land; socks before shoes: zero pending goes first”
- Flood new land→Each unseen land cell = +1 island, then mark the whole island
- BFS rings→Fewest steps or minutes on a grid
- Socks before shoes→Topological order respects every dependency
- Zero pending goes first→Queue tasks with no prerequisites left
- Stuck = cycle→If tasks remain but none are ready, it's impossible
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Courses 0→1, 0→2, 1→3, 2→3: pending = [0, 1, 1, 2] → take 0 (1 and 2 drop to 0) → take 1 (3 drops to 1) → take 2 (3 drops to 0) → take 3. Order [0, 1, 2, 3]. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 6 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Common mistakes
- Marking seen too late. Mark a cell when you add it to the queue, not when you pop it, or it gets added many times.
- Going out of bounds. Check row and column limits before reading a neighbour.
- Edge direction. “[course, prerequisite]” means the edge goes prerequisite → course.
Where to go next
BFS and DFS explore what's already there. What if you have to build every possible answer: all subsets, all arrangements, every way to place queens? That's backtracking.
Key takeaways
- ✓A grid is a graph: cells are nodes, 4 neighbours are edges.
- ✓Number of Islands: each unseen land cell starts a flood fill.
- ✓BFS finds the fewest steps; start from many sources for “minutes to spread”.
- ✓Topological sort orders tasks after their prerequisites (Kahn's algorithm).
- ✓If tasks remain but none are ready, there's a cycle: impossible.
Frequently asked questions
How do you solve Number of Islands?
Scan every cell. When you find land that isn't marked as seen, add one to the count and flood-fill the whole island (BFS or DFS to its 4 neighbours), marking every cell as seen. Each cell is processed once, so it's O(rows × cols).
Should I use BFS or DFS on a grid?
For counting or filling regions, either works. For the shortest number of steps (rotting oranges, shortest path in a maze, word ladder), use BFS: it explores in rings, so the first time you reach a cell is the fewest steps.
What is topological sort in simple words?
An order of tasks where every task comes after the tasks it depends on, like taking courses only after their prerequisites, or putting on socks before shoes. It only exists if there are no cycles.
How does Kahn's algorithm work?
Count each task's pending prerequisites (its in-degree). Put every task with 0 pending in a queue. Repeatedly take one, add it to the order, and lower the count of tasks that needed it; any that reach 0 join the queue. If the order ends up shorter than the number of tasks, there's a cycle.
Is a grid really a graph?
Yes. Each cell is a node and it has edges to its up, down, left and right neighbours. Thinking of grids as graphs lets you reuse BFS and DFS from Part 9 directly.
🧠 Quick check: grid BFS and topological sort
1. Fewest minutes until all oranges rot (rot spreads to neighbours each minute). Which traversal?
2. Why do we mark cells as seen when flood-filling?
3. Courses: B needs A, C needs B, A needs C. Topological order?
4. In Kahn's algorithm, which tasks go into the queue first?
Checking your access…