I am sure we are all familiar with graphs, given that this whole note repo is graph-based! But in computer science, graphs are a fundamental data structure used to model relationships between entities. They consist of vertices (or nodes) and edges (connections between nodes).

This will deal with defining graphs formally, and some common algorithms that operate on them.


Undirected Graphs

Undirected graphs are defined as:

where:

  • is the set of vertices (or nodes).
  • is the set of edges, which are unordered pairs of vertices. An edge
  • Captures a bidirectional relationship between two vertices.
  • Graph size parameters:
    • (number of vertices)
    • (number of edges)

Example

Say we define a graph with the following parameters:

This would yield a graph looking like:

Question

What is the minimum and maximum numbers of edges in an undirected graph with vertices?


Directed Graphs

Similarly, directed graphs are defined as:

Where:

  • is the set of vertices (or nodes).
  • is the set of edges between ordered pairs of vertices.
  • Captures pairwise relationships between two vertices, but in a specific direction (from one vertex to another).
  • Graph size parameters:
    • (number of vertices)
    • (number of edges)

Returning to the Example

Going back to the same definition from before, lets see what happens when we construct a directed graph from the same parameters:

We get:

Looks quite similar! But with one obvious change.

Question

What is the minimum and maximum numbers of edges in a directed graph with vertices?


Alternative Representation

Graphs can be represented in various ways, and one common method is using an Adjacency Matrix. An adjacency matrix is a 2D array where the rows and columns represent the vertices of the graph, and the entries indicate whether there is an edge between the vertices.

Another way to represent them is with an Adjacency List. Like the adjacency matrix, it represents which vertices are connected to which other vertices, but does so in a more space-efficient manner for sparse graphs.

Comparing Complexity of the Two

ComplexityAdjacency MatrixAdjacency List
Storage space
Check edge
Find all edges

Side note:

  • As a graph becomes dense, approaches because approaches
  • As a graph becomes sparse, approaches because approaches