Graph basics
On this page 8 topics
Overview
Topics
- Vertices
- edges
- BFS
- DFS
- common applications
Learn first
71 min of reading · 3 h of practice (estimate)
Learning outcomes
- Represent a graph with an adjacency list.
- Implement BFS and DFS and choose between them.
- Find a shortest path in an unweighted graph with BFS.
- Recognize graph problems in real systems (dependencies, networks, routes).
Lessons
Lab and exercises
Lab
BEG-043-LAB1 · Metro route finder
Outcomes: 1–4 · Time: ~3 h
- Load a small metro map (a text file of "station-station" lines) into an adjacency list.
- Implement BFS that returns the fewest-stops route between two stations.
- Handle unknown and unreachable stations without crashing.
- Add a DFS "can I get there at all" check and say when you would use it instead of BFS.
Acceptance: correct routes; unreachable stations handled.
Exercises (assessment: 3 problems)
| ID | Outcome | Task |
|---|---|---|
| BEG-043-EX01 | 1 | Write the adjacency list for edges A-B, A-C, B-D, C-D, D-E (undirected). |
| BEG-043-EX02 | 2 | Write the BFS visiting order from A for the graph in EX01 (visit neighbors in alphabetical order). |
| BEG-043-EX03 | 2 | Write the DFS visiting order from A for the same graph, same neighbor order. |
| BEG-043-EX04 | 3 | Using BFS, give the shortest path from A to E and its number of edges. |
| BEG-043-EX05 | 4 | Name the nodes and edges of: a course prerequisite plan; a social network; a map of airports and flights. Say whether each is directed. |
| BEG-043-EX06 | 2 | Explain what happens if BFS has no visited set on a graph with a cycle. |
Show solutions
- EX01 A: [B, C]; B: [A, D]; C: [A, D]; D: [B, C, E]; E: [D].
- EX02 A, B, C, D, E.
- EX03 A, B, D, C, E (A -> B -> D -> C, back to D -> E).
- EX04 A -> B -> D -> E (or via C), 3 edges.
- EX05 Prerequisites: courses are nodes, "needs" are directed edges. Social network: people are nodes; "friend" is undirected, "follows" is directed. Airports: nodes airports, edges flights, usually directed.
- EX06 It keeps re-adding the same nodes around the cycle and never finishes (an infinite loop or a memory error).
Quiz
Outcomes: O1 adjacency list · O2 BFS and DFS · O3 shortest path · O4 graph problems in systems.
A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.
Practical part
Three problems (BEG-043-EX02, EX03, EX04) plus the metro route finder lab and exercises EX01, EX05, EX06. Pass: at least 2 of 3 problems correct, correct routes, unreachable stations handled, and at least 8 of 10 quiz answers correct.
Common mistakes
Forgetting a visited set (infinite loops).
Assessment
3 problems.
Career relevance
Dependency mapping (SRC-009) and service graphs.