Directed vs Undirected Graphs

Learn Directed vs Undirected Graphs with practical examples, explanations, best practices, and real-world coding techniques.

Directed vs Undirected Graphs

One of the first decisions when working with a graph is determining whether its edges have a direction. This gives us two fundamental graph types: directed graphs and undirected graphs.

In an undirected graph, a connection between two vertices works in both directions. In a directed graph, every edge has a specific source and destination, so the connection can be followed only in the indicated direction unless another edge provides a reverse route.

What Is an Undirected Graph?

An undirected graph is a graph in which edges do not have a direction. If vertex A is connected to vertex B, B is also directly connected to A.

A --- B
|     |
C --- D

For example, if A is connected to B, you can travel from A to B and from B to A using the same edge.

What Is a Directed Graph?

A directed graph, also called a digraph, contains edges with a specific direction. Each edge has a source vertex and a destination vertex.

A ---> B
|      |
v      v
C ---> D

The edge A → B means that A points to B. It does not automatically mean that B points back to A.

The Core Difference

Property Undirected Graph Directed Graph
Edge direction No direction Has direction
Connection A-B means A connects to B and B connects to A A → B means A points to B
Degree One degree value per vertex In-degree and out-degree
Reverse traversal Naturally possible Requires a reverse edge or another route
Typical examples Road connections, friendships Web links, dependencies, following relationships

Edge Representation

The way an edge is interpreted is the main difference between these graph types.

Undirected Edge

A --- B

The edge represents the relationship {A, B}. Both vertices can reach each other directly.

Directed Edge

A ---> B

The edge represents an ordered relationship from A to B. The reverse relationship B → A would need its own edge.

Degrees Are Different

Degree is calculated differently depending on whether the graph is directed or undirected.

Undirected Graph Degree

    B
    |
C---A---D

Vertex A has four incident edges, so its degree is 4.

Directed Graph Degree

A ---> B
^      |
|      v
C <--- D
  • In-degree: Number of edges entering a vertex.
  • Out-degree: Number of edges leaving a vertex.

For a directed graph, the total in-degree across all vertices equals the total out-degree, and both equal the number of directed edges.

Traversal Behavior

Graph traversal algorithms such as BFS and DFS work with both directed and undirected graphs, but the neighbors considered during traversal are different.

Undirected Traversal

A --- B

Starting at A allows you to visit B. Starting at B also allows you to visit A.

Directed Traversal

A ---> B

Starting at A allows you to follow the edge to B. Starting at B does not allow you to follow that same edge back to A.

Adjacency List Representation

An adjacency list stores the vertices directly connected to each vertex. For an undirected graph, an edge is normally stored for both endpoints.

const undirectedGraph = {
  A: ['B'],
  B: ['A', 'C'],
  C: ['B']
};

The A-B connection appears in both A's and B's lists.

In a directed graph, only the destination is normally added to the source's adjacency list.

const directedGraph = {
  A: ['B'],
  B: ['C'],
  C: []
};

A points to B and B points to C. There is no automatic edge from B back to A.

Adjacency Matrix Representation

An adjacency matrix uses a two-dimensional matrix to represent whether an edge exists between two vertices.

For an undirected graph, the matrix is symmetric because an edge between A and B exists in both directions.

    A B C
A   0 1 0
B   1 0 1
C   0 1 0

In a directed graph, the matrix does not have to be symmetric.

    A B C
A   0 1 0
B   0 0 1
C   0 0 0

Here, A → B and B → C exist, but the reverse edges do not.

Real-World Examples

Social Friendships

A mutual friendship can be modeled as an undirected relationship when both people have the same connection to each other.

Social Media Following

Following relationships are naturally directed. If user A follows user B, it does not necessarily mean B follows A.

Road Networks

A road between two locations can be represented as an undirected edge when traffic can travel in both directions. One-way roads require directed edges.

Web Pages

A hyperlink from one page to another can be modeled as a directed edge because the link originates from one page and points to another.

Task Dependencies

If task A must be completed before task B, the relationship can be represented as A → B. Directed graphs are useful for dependency graphs and topological sorting.

Paths and Reachability

Direction changes the meaning of reachability. In an undirected graph, if there is a path from A to B, the same path can generally be followed from B to A in reverse.

In a directed graph, a path from A to B does not imply that a path exists from B to A.

A ---> B ---> C

A can reach C, but C cannot reach A using these directed edges.

Connectivity in Directed Graphs

Directed graphs introduce additional connectivity concepts because direction matters.

Strong Connectivity

A directed graph is strongly connected when every vertex can reach every other vertex following the direction of the edges.

A ---> B
^       |
|       v
+-------C

In this example, each vertex can eventually reach the others.

Weak Connectivity

A directed graph is weakly connected when ignoring the direction of its edges produces a connected undirected graph.

Cycles

Both graph types can contain cycles, but the direction of edges must be considered in a directed graph.

Undirected Cycle

A --- B
|     |
D --- C

A-B-C-D-A forms an undirected cycle.

Directed Cycle

A ---> B
^       |
|       v
+-------C

A → B → C → A forms a directed cycle because all edges can be followed in sequence.

Weighted Directed and Undirected Graphs

Direction and weight are separate properties. A graph can be directed or undirected and can also be weighted or unweighted.

Undirected weighted:

A --- 10 --- B


Directed weighted:

A --- 10 ---> B

In a directed weighted graph, the reverse edge can have a different weight if it exists.

A --- 10 ---> B
A <--- 7 ---- B

These are two separate directed edges with potentially different meanings or costs.

JavaScript Example

The following example shows the practical difference between storing an undirected graph and a directed graph using adjacency lists.

const undirectedGraph = {
  A: ['B'],
  B: ['A', 'C'],
  C: ['B']
};

const directedGraph = {
  A: ['B'],
  B: ['C'],
  C: []
};

console.log('Undirected neighbors of B:', undirectedGraph.B);
console.log('Directed neighbors of B:', directedGraph.B);

In the undirected graph, B is connected to both A and C, and A also lists B as a neighbor. In the directed graph, B has an outgoing connection to C, but there is no automatic connection from B back to A.

How to Identify the Graph Type

Before implementing a graph algorithm, inspect the relationship represented by each edge. Ask these questions:

  1. Does the connection work in both directions?
  2. Does each edge have a source and destination?
  3. Does the reverse connection need a separate edge?
  4. Does the problem require in-degree and out-degree?
  5. Can a path be followed only according to edge direction?

These questions usually make it clear whether the graph should be modeled as directed or undirected.

Which Algorithms Are Commonly Used?

Problem Undirected Graph Directed Graph
BFS Common Common
DFS Common Common
Connected components Common Different directed connectivity concepts apply
Topological sorting Not based on ordinary undirected edges Requires a directed acyclic graph
Dijkstra's algorithm Can be used with non-negative weights Can be used with non-negative weights
Minimum spanning tree Defined for weighted undirected graphs Requires different concepts such as directed spanning structures

Common Mistakes

  • Assuming A → B automatically means B → A.
  • Adding reverse edges to a directed graph when the problem does not define them.
  • Using ordinary degree terminology without distinguishing in-degree and out-degree in directed graphs.
  • Assuming reachability from A to B means B can reach A.
  • Forgetting to represent both endpoints when constructing an undirected adjacency list.
  • Treating an undirected graph as directed during BFS or DFS and accidentally changing the problem.
  • Ignoring edge direction when detecting cycles or analyzing dependencies.

Key Takeaways

  • An undirected graph has edges without direction.
  • A directed graph has edges with a specific source and destination.
  • An undirected edge connects two vertices in both directions.
  • A directed edge does not imply a reverse connection.
  • Undirected graphs use degree, while directed graphs distinguish in-degree and out-degree.
  • Adjacency lists store both endpoints of an undirected edge but normally store only the destination for a directed edge.
  • Direction affects paths, reachability, cycles, connectivity, and algorithm behavior.
  • Real-world relationships such as friendships, one-way roads, hyperlinks, and task dependencies can help determine the appropriate graph type.

Code Examples

const graph = {};

function addEdge(graph, a, b) {
  if (!graph[a]) graph[a] = [];
  if (!graph[b]) graph[b] = [];

  graph[a].push(b);
  graph[b].push(a);
}

addEdge(graph, 'A', 'B');
addEdge(graph, 'B', 'C');
addEdge(graph, 'A', 'C');

console.log(graph);
// A can reach B and C
// B can reach A and C
    
const graph = {};

function addDirectedEdge(graph, from, to) {
  if (!graph[from]) {
    graph[from] = [];
  }

  if (!graph[to]) {
    graph[to] = [];
  }

  graph[from].push(to);
}

addDirectedEdge(graph, 'A', 'B');
addDirectedEdge(graph, 'B', 'C');

console.log(graph);
// A -> B
// B -> C
// C has no outgoing edges
    
const directedGraph = {
  A: ['B'],
  B: ['C'],
  C: []
};

function canReach(graph, start, target) {
  const visited = new Set();
  const queue = [start];

  while (queue.length > 0) {
    const current = queue.shift();

    if (current === target) {
      return true;
    }

    if (visited.has(current)) {
      continue;
    }

    visited.add(current);

    for (const neighbor of graph[current]) {
      if (!visited.has(neighbor)) {
        queue.push(neighbor);
      }
    }
  }

  return false;
}

console.log(canReach(directedGraph, 'A', 'C')); // true
console.log(canReach(directedGraph, 'C', 'A')); // false
    

Pro Tip

Before writing BFS, DFS, or any graph algorithm, determine whether edges are directed. In an undirected graph, adding A-B normally means both A can reach B and B can reach A. In a directed graph, A → B only creates the connection from A to B unless a separate reverse edge exists.

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.