19 min read Modeling Networks & Relationships Lesson 10 of 12
Course 05 · Part 3 — Advanced Networks & Trees

Graph: Modeling Relationships and Interconnected Networks

Beyond isolated values—when the links between data points become the primary data itself

Every data structure we have studied so far—Arrays, Linked Lists, Stacks, Queues, Hash Tables, Trees, BSTs, and Heaps—organized data sequentially or in strict top-down parent-child hierarchies. But the real world rarely fits into neat single-parent lineages. In road networks, multiple alternative highways link cities; in social networks, friends share mutual connections with circular loops; on the World Wide Web, billions of hyperlinks cross-reference one another arbitrarily. In software engineering, when entities connect with arbitrary complexity, computer scientists rely on the most universal structure of all: the Graph.

The Core Question: “Who is Connected to Whom?”

You can drive from Dhaka to Chittagong directly along the national highway, or divert through Sylhet and Comilla. On social platforms, Rahim and Karim are mutual friends who both know Salim. When viewing a Wikipedia article, you can click through twenty different hyperlinks. Here, individual values matter far less than the topological connections linking them together.

01 What is a Graph?

Formally and intuitively defined:

“A Graph is a non-linear data structure consisting of two core mathematical sets: a finite collection of Nodes (or Vertices) representing entities, and a collection of Edges representing the relationships or connections between them. Formally, $G = (V, E)$.”

Consider this canonical four-vertex graph:

          A ──────── B
          │          │
          │          │
          C ──────── D
        
Vertices / Nodes: $V = \{A, B, C, D\}$ (The Entities)
Edges: $E = \{(A,B), (B,D), (D,C), (C,A)\}$ (The Links)
“Nodes represent Entities; Edges represent Relationships.”

02 Nodes (Vertices) and Edges

The fundamental building blocks of all network topologies:

Node or Vertex (plural: Vertices)

An individual discrete entity or object in the network. In social networks, this represents an account holder (e.g., Alice, Bob); in maps, an intersection or city (e.g., Dhaka, London); in networks, a server or router.

Edge or Link

The bridge or connection between two vertices. Mutual friendship on Facebook, a two-lane highway between towns, or a clickable hyperlink between web pages.

03 Tree vs. Graph: The Presence of Cycles

Where does the strict boundary between trees and graphs lie?

Tree (Lesson 5.7)
        A ← Single Root
       / \
      B   C
     / \
    D   E
          
• Zero circular paths (Acyclic)
• Strict parent-child hierarchy
• Exactly $N - 1$ edges for $N$ nodes
Graph (Lesson 5.10)
        A ───── B
        │ ╲   ╱ │
        │   ╳   │  ← Arbitrary links
        │ ╱   ╲ │
        C ───── D
          
• Can contain Cycles: $A \to B \to D \to C \to A$
• No designated root or parent
• Arbitrary number of edges
The Golden Rule to Remember:

“Every tree is a graph, but not every graph is a tree.” A tree is simply a connected, undirected, acyclic graph.

04 Two Iconic Real-World Graphs

How everyday software systems model reality as graphs:

1. Road Transit Network

Cities as vertices and connecting highways as edges:

          Dhaka
         /     \
    Sylhet     Comilla
       \         /
       Chittagong
            

GPS navigation asks: "What is the fastest route from Dhaka to Chittagong with minimal congestion?"

2. Social Friendship Graph

People as vertices and reciprocal friendships as edges:

         Rahim
        /     \
    Karim ─── Salim
        \     /
         Nadia
            

Recommendation engines query: "Who are the mutual friends between Karim and Salim, and how many hops separate them?"

05 Directed vs. Undirected Graphs

Whether connections travel both ways or only in a single direction distinguishes the two major categories of graphs:

Undirected Graph (Bidirectional)

Edges possess no orientation. If node $A$ is connected to node $B$, you can traverse equally from $A$ to $B$ or from $B$ to $A$.

A ──────── B
Symmetric two-way transit

Real-world analogies: Facebook friendships, two-way roads.

Directed Graph (Digraph)

Edges carry a strict orientation (arrows). $A \to B$ means you can travel from $A$ to $B$, but you cannot travel backwards unless an explicit reverse edge exists.

A ───────> B
Unidirectional flow

Real-world analogies: Twitter/X followers, one-way streets, web hyperlinks.

06 Weighted Graphs: Quantifying Connection Cost

In practical engineering, connections are not equal. When a numerical value or cost (Weight) is attached to each edge, the structure becomes a Weighted Graph:

                    Dhaka
                   /     \
            240 km/       \ 100 km
                 /         \
            Sylhet         Comilla
                 \         /
            180 km\       / 150 km
                   \     /
                 Chittagong
        

Weights can represent any physical or operational metric:

🚗 Distance: Dhaka-Chittagong (250 km)
⚡ Latency: Server A-B (20 ms ping)
💰 Financial Cost: Airline ticket ($250)

07 Node Degree (In-degree & Out-degree)

The count of edges connected to a specific vertex is defined as its Degree:

In Undirected Graphs:

The total number of incident edges. A Facebook user with 300 friends has a vertex degree of 300.

In Directed Graphs (Digraphs):
  • In-degree: Incoming arrows entering the node (e.g., your follower count).
  • Out-degree: Outgoing arrows leaving the node (e.g., your following count).

08 Paths and the Shortest Path Problem

A sequence of consecutive edges connecting a start vertex to an end vertex constitutes a Path:

            A ────── 5 ────── B
             \               /
            2 \             / 1
               \           /
                     C
        
• Direct route ($A \to B$): Cost = 5
• Detour route ($A \to C \to B$): Cost = $2 + 1 =$ 3 (Cheaper path!)

Solving the Shortest Path Problem across massive graphs is one of computer science's greatest milestones, solved via algorithms such as Dijkstra, Bellman-Ford, and $A^*$.

09 How are Graphs Stored in Memory? (Matrix vs. List)

Drawing graphs on paper is intuitive, but machines require concrete data structures. Two primary representations dominate:

1 Adjacency Matrix (2D Grid)

A 2D array of size $V \times V$. If an edge connects node $i$ to node $j$, then matrix[i][j] = 1 (or weight); otherwise, 0.

          A  B  C  D
       A [0, 1, 1, 0]  ← A connected to B and C
       B [1, 0, 0, 1]  ← B connected to A and D
       C [1, 0, 0, 1]  ← C connected to A and D
       D [0, 1, 1, 0]  ← D connected to B and C
          

Advantage: Instant $O(1)$ edge existence check between any two nodes.
Disadvantage: Memory consumption is $O(V^2)$. A graph of 1,000,000 vertices requires a trillion cells, most of which sit empty!

2 Adjacency List (Linked / Array Neighbors)

Each vertex maintains a compact array or linked list containing only its immediate neighbors.

       A → [B, C]
       B → [A, D]
       C → [A, D]
       D → [B, C]
          

Advantage: Memory footprint is strictly $O(V + E)$. Incredibly efficient for real-world sparse graphs!
Disadvantage: Verifying if edge $(u, v)$ exists requires scanning $u$'s neighbor list ($O(\text{degree})$).

10 Adjacency Matrix vs. Adjacency List

Choosing the optimal representation for your workload:

Dimension Adjacency Matrix Adjacency List
Space Complexity $O(V^2)$ $O(V + E)$ (Highly compact)
Edge Existence Check $O(1)$ (Instant coordinate lookup) $O(\text{Degree})$
Iterate Over Neighbors $O(V)$ (Must scan entire row) $O(\text{Degree})$ (Pre-filtered)
Ideal Workload Dense Graphs ($E \approx V^2$) Sparse Graphs ($E \ll V^2$, real-world networks)

11 Graph Traversals: BFS vs. DFS

Systematically visiting every reachable vertex without getting trapped in infinite circular loops:

BFS (Breadth-First Search)

Spreads outward like concentric ripples in a pond. Explores all direct neighbors at distance 1 before moving to distance 2.

Backing Structure: Queue (FIFO)
Core Superpower: Guaranteed to find the shortest path in unweighted graphs!
DFS (Depth-First Search)

Plunges as deep as possible down a single branch until it hits a dead end, then backtracks to explore alternatives (like navigating a labyrinth).

Backing Structure: Stack (LIFO) or Call Recursion
Core Superpower: Cycle detection, maze solving, topological sorting!

12 DAGs & Software Package Dependencies

A special class of graphs underpins software infrastructure: the Directed Acyclic Graph (DAG)—edges have directions, but circular loops are strictly absent.

                   Main Web App
                   /          \
                  ↓            ↓
            Auth Service     Payment Engine
                  \            /
                   ↓          ↓
                  Database Driver
        

Package managers (like npm, pip) and modern bundlers (like Vite) model code modules as DAGs, computing valid installation/compilation sequences via Topological Sorting.

🎮 Interactive Visual Graph Simulator & Memory Inspector

Select nodes, toggle directed edge orientations, run animated traversals, and watch how both the Adjacency Matrix and Adjacency List generate in real time:

Graph Type:
🎮 Click any node to inspect its degree and memory neighbor list.
1. Adjacency Matrix (2D Grid): $O(V^2)$
2. Adjacency List (Linked / Array): $O(V + E)$

💡 Concept Check: Test Your Intuition

1. What is the fundamental structural difference between a Tree and a general Graph?

2. For real-world sparse graphs (like social friendship networks or road maps), which in-memory representation is significantly more memory-efficient?

3. In an unweighted graph, which traversal algorithm guarantees finding the shortest path (minimum number of hops) from start to destination?

13 Our Data Structures Journey

The progressive architectural ladder of computer science:

• Array: Contiguous index-based memory sequence
• Linked List: Pointer-connected chains of fragmented nodes
• Stack: Last In, First Out (LIFO)
• Queue: First In, First Out (FIFO)
• Hash Table: Key → Value ($O(1)$ direct hash lookups)
• Tree: Top-down hierarchical lineages
• Binary Search Tree: Hierarchy + Ordering = $O(\log n)$ search
• Heap: Hierarchy + Priority = Instant $O(1)$ root access
• Graph: Generalized network & relationship modeling (Vertices, Edges, Cycles, Connectivity)

14 Next Challenge: Text & Prefix Search Optimization

We have conquered numbers, objects, and vast geographic network topologies. But what happens when our primary data type is Text or Strings?

When typing ca into a search engine or mobile keyboard:
    ca ──┬──> cat
         ├──> car
         ├──> camera
         └──> cancel
        

Scanning a dictionary of hundreds of thousands of words for common prefixes is sluggish using standard arrays or hash tables.

To solve this character by character with lightning efficiency, computer science invented:

Coming Up in Lesson 11

Trie (Prefix Tree)

How character-by-character branching powers instant dictionary lookups, search engine autocomplete, and spell-checking engines.

🧠 Key Takeaways

1. Vertices & Edges

Vertices model entities or objects; edges model the connections, paths, or relationships linking them.

2. Freedom of Cycles

Unlike trees, graphs do not enforce a strict root hierarchy; circular cycles and multiple paths are natural and common.

3. Adjacency List Dominance

Because real-world networks are sparse, the $O(V + E)$ Adjacency List is the standard practical memory representation.

4. BFS vs. DFS

BFS uses a Queue to find shortest hop paths; DFS uses a Stack/Recursion to plunge deep for cycle detection and dependency sorting.