🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Graph Fundamentals — Vertices, Edges, Directed vs Undirected — Complete Beginner Guide

Data Structures FoundationsGraph Fundamentals — Vertices, Edges, Directed vs Undirected🟢 Free Lesson

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.

python
# 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

TermMeaningExample
Vertex or nodeAn entityUser, city, webpage
EdgeA relationshipFriendship, road, hyperlink
EndpointVertex an edge touchesBoth ends of a road
Isolated vertexNo edgesNew 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.

PropertyUndirectedDirected
Edge storageOne undirected edgeOne ordered arc
DegreeCount of touching edgesSplit into in-degree and out-degree
Path directionEither wayMust follow arrows
ExampleRoads without one-way rulesOne-way streets
python
# 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.

GraphEdge DataTypical Algorithms
UnweightedPresence onlyBFS for fewest hops
WeightedPositive or signed costsDijkstra, Bellman-Ford
Negative weightsNegative costs presentBellman-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.

python
# 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

DomainVerticesEdges
Social networkPeopleFriendships or follows
Road mapIntersectionsRoads with lengths
WebPagesHyperlinks
DependenciesTasksMust-finish-before links
MoleculesAtomsChemical bonds
RecommendationUsers and itemsInteractions

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.

python
# 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

  1. Model your favorite app as a graph and name the vertices and edges.
  2. Give one example of a directed graph and one of an undirected graph from daily life.
  3. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement