Graph Fundamentals — Vertices, Edges, Directed vs Undirected — Complete Beginner Guide
Learning Objectives
- Define vertices and edges precisely
- Tell directed graphs from undirected graphs
- Explain weighted and unweighted edges
- Compute degree and spot simple paths
- Model real systems as graphs
What Is a Graph?
A graph is a collection of vertices, also called nodes, plus edges that connect pairs of vertices. Graphs model relationships rather than sequences or hierarchies alone.
Formally, a graph G holds a set of vertices V and a set of edges E drawn from pairs in V.
# Undirected unweighted graph in pure Python
vertices = ["A", "B", "C", "D"]
edges = [
("A", "B"),
("A", "C"),
("B", "C"),
("C", "D"),
]
def neighbors(graph_edges, node):
out = []
for a, b in graph_edges:
if a == node:
out.append(b)
elif b == node:
out.append(a)
return out
print(neighbors(edges, "A")) # B and C
Vertices and Edges
| Term | Meaning | Example |
|---|---|---|
| Vertex or node | An entity | User, city, webpage |
| Edge | A relationship | Friendship, road, hyperlink |
| Endpoint | Vertex an edge touches | Both ends of a road |
| Isolated vertex | No edges | New empty account |
Directed versus Undirected
Undirected
Edges have no arrow. Friendship on a classic social network is mutual. If A connects to B, then B connects to A.
Directed
Edges have direction, forming arcs. Follows on social media or web links can be one-way. A can follow B without B following A.
| Property | Undirected | Directed |
|---|---|---|
| Edge storage | One undirected edge | One ordered arc |
| Degree | Count of touching edges | Split into in-degree and out-degree |
| Path direction | Either way | Must follow arrows |
| Example | Roads without one-way rules | One-way streets |
# Directed graph adjacency map
digraph = {
"A": ["B", "C"],
"B": ["D"],
"C": ["D"],
"D": [],
}
def out_degree(graph, node):
return len(graph[node])
def in_degree(graph, node):
count = 0
for src in graph:
if node in graph[src]:
count += 1
return count
print(out_degree(digraph, "A"), in_degree(digraph, "D"))
Weighted versus Unweighted
A weight attaches a number to an edge such as distance, cost, or time. Shortest path algorithms care about weights.
| Graph | Edge Data | Typical Algorithms |
|---|---|---|
| Unweighted | Presence only | BFS for fewest hops |
| Weighted | Positive or signed costs | Dijkstra, Bellman-Ford |
| Negative weights | Negative costs present | Bellman-Ford required |
Paths, Cycles, and Connectivity
A path is a sequence of vertices where each step follows an edge. A cycle returns to the starting vertex. A graph is connected when every pair of vertices shares some path.
In directed graphs, strong connectivity requires a path in both directions between every pair.
# Tiny path search on an undirected adjacency list
graph = {
"A": ["B"],
"B": ["A", "C"],
"C": ["B", "D"],
"D": ["C"],
}
def has_path(graph, start, goal, seen=None):
if seen is None:
seen = set()
if start == goal:
return True
seen.add(start)
for nxt in graph[start]:
if nxt not in seen and has_path(graph, nxt, goal, seen):
return True
return False
print(has_path(graph, "A", "D")) # True
Common Real-World Models
| Domain | Vertices | Edges |
|---|---|---|
| Social network | People | Friendships or follows |
| Road map | Intersections | Roads with lengths |
| Web | Pages | Hyperlinks |
| Dependencies | Tasks | Must-finish-before links |
| Molecules | Atoms | Chemical bonds |
| Recommendation | Users and items | Interactions |
Dense versus Sparse
A dense graph has close to the maximum possible edges. A sparse graph has far fewer. Sparse graphs favor adjacency lists. Dense graphs can favor adjacency matrices, covered later.
Graph Modeling Exercises
Pick everyday systems and force yourself to write the vertex and edge sets. A ride-sharing app might use drivers and riders as vertices with availability edges. A course catalog uses courses as vertices and prerequisite arrows as directed edges. A protein interaction map uses proteins and measured bindings.
After modeling, ask whether the graph is directed, weighted, sparse, or dynamic. Those four answers steer representation and algorithm choices before you open an editor.
# Tiny dependency graph check
prereqs = {
"algebra": [],
"calculus": ["algebra"],
"physics": ["calculus", "algebra"],
"lab": ["physics"],
}
def ready(course, done):
return all(p in done for p in prereqs[course])
print(ready("algebra", set())) # True
print(ready("physics", {"algebra"})) # False
Strong modeling is half the battle. Many hard-seeming problems become ordinary BFS or union-find once the vertices and edges are stated cleanly.
Key Takeaways
💡
- Graphs store entities as vertices and relationships as edges
- Undirected edges are mutual; directed edges have arrows
- Weights turn presence into cost for shortest path work
- Degree counts connections; directed graphs split in and out
- Roads, follows, and task dependencies are everyday graph models
Practice Questions
- Model your favorite app as a graph and name the vertices and edges.
- Give one example of a directed graph and one of an undirected graph from daily life.
- Explain the difference between a path and a cycle in two sentences.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions