Graphs
Nodes and edges: explore with DFS or BFS, marking what you've visited so you never go round in circles.
Spot it
Signals in the questionA grid where cells connect to neighbours (islands, rotting oranges, flood fill).
Things that depend on each other (courses, tasks): edges and maybe cycles.
"Connected", "reachable", "how many groups", "shortest number of steps".
The idea
O(rows × cols) time · O(rows × cols) worst-case recursion spaceGo through every cell. When you find land you haven't seen, that's a new island: count it, then flood-fill (DFS) all its land so you don't count it again. Marking visited is what keeps it O(cells).
Template · Count components with DFS
1def num_islands(grid):2 rows, cols = len(grid), len(grid[0])3 def sink(r, c):4 if r < 0 or c < 0 or r >= rows or c >= cols or grid[r][c] != 1:5 return6 grid[r][c] = 0 # visited7 sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1)8 count = 09 for r in range(rows):10 for c in range(cols):11 if grid[r][c] == 1:12 count += 113 sink(r, c)14 return count
The template, filled in for Number of Islands. The highlighted lines are the part every problem of this kind shares.
The best, free
One of eachPractice set
Loading your mission…
Common mistakes
1Not marking cells visited, so the search loops forever.
2Checking bounds after reading grid[r][c]: out-of-range errors.
3Using DFS for shortest steps: BFS finds the fewest steps in an unweighted graph.
Check yourself
Question 1 of 2"Fewest moves from start to exit in a maze." DFS or BFS?