Vertex in Graph Theory

In graph theory, a vertex is a fundamental component of a graph. It represents a node or point within the graph structure. Vertices can be connected to one another through edges, forming the backbone of graph-based data structures. This concept is crucial in various applications, from network design to algorithm development.

Definition and Representation

A vertex, also known as a node, is a single point in a graph. It can be connected to other vertices via edges, which are the links or connections between nodes. In the context of a graph framework, vertices are typically stored in a list and can be of any data type, providing flexibility in representing diverse kinds of data. This allows for the representation of complex structures, such as social networks, transportation systems, and more.

Graph Framework

The graph framework is designed to associate vertices with edges, allowing for the representation and manipulation of complex networks. The framework is flexible, enabling the use of various data types for vertices, which can be tailored to specific problems or datasets.

Edge Class

The Edge class is a fundamental part of the graph framework, representing the connection between two vertices. Each edge is defined by two integer indices, u and v, which refer to the "from" and "to" vertices, respectively. The class includes a method to reverse the direction of an edge, which is particularly useful in directed graphs.

Listing 4.1. edge.py

from __future__ import annotations
from dataclasses import dataclass

@dataclass
class Edge:
    u: int # the "from" vertex
    v: int # the "to" vertex

    def reversed(self) -> Edge:
        return Edge(self.v, self.u)

    def __str__(self) -> str:
        return f"{self.u} -> {self.v}"

Graph Class

The Graph class is responsible for managing the vertices and their associated edges. It allows for the addition of vertices and edges, and provides methods to retrieve information about the graph's structure, such as the number of vertices and edges, and the neighbors of a given vertex.

Listing 4.2. graph.py

from typing import TypeVar, Generic, List, Optional
from edge import Edge

V = TypeVar('V') # type of the vertices in the graph

class Graph(Generic[V]):
    def __init__(self, vertices: List[V] = []) -> None:
        self._vertices: List[V] = vertices
        self._edges: List[List[Edge]] = [[] for _ in vertices]

The Graph class includes methods for adding vertices and edges, retrieving vertex indices, and finding neighbors and edges associated with a vertex. This design allows for efficient manipulation and querying of the graph structure.

Listing 4.3. graph.py continued

@property
def vertex_count(self) -> int:
    return len(self._vertices) # Number of vertices

@property
def edge_count(self) -> int:
    return sum(map(len, self._edges)) # Number of edges

# Add a vertex to the graph and return its index
def add_vertex(self, vertex: V) -> int:
    self._vertices.append(vertex)
    self._edges.append([]) # Add empty list for containing edges
    return self.vertex_count - 1 # Return index of added vertex

# This is an undirected graph,
# so we always add edges in both directions
def add_edge(self, edge: Edge) -> None:
    self._edges[edge.u].append(edge)
    self._edges[edge.v].append(edge.reversed())

# Add an edge using vertex indices (convenience method)
def add_edge_by_indices(self, u: int, v: int) -> None:
    edge: Edge = Edge(u, v)
    self.add_edge(edge)

# Add an edge by looking up vertex indices (convenience method)
def add_edge_by_vertices(self, first: V, second: V) -> None:
    u: int = self._vertices.index(first)
    v: int = self._vertices.index(second)
    self.add_edge_by_indices(u, v)

# Find the vertex at a specific index
def vertex_at(self, index: int) -> V:
    return self._vertices[index]

# Find the index of a vertex in the graph
def index_of(self, vertex: V) -> int:
    return self._vertices.index(vertex)

# Find the vertices that a vertex at some index is connected to
def neighbors_for_index(self, index: int) -> List[V]:
    return list(map(self.vertex_at, [e.v for e in self._edges[index]]))

# Look up a vertice's index and find its neighbors (convenience method)
def neighbors_for_vertex(self, vertex: V) -> List[V]:
    return self.neighbors_for_index(self.index_of(vertex))

# Return all of the edges associated with a vertex at some index
def edges_for_index(self, index: int) -> List[Edge]:
    return self._edges[index]

# Look up the index of a vertex and return its edges (convenience method)
def edges_for_vertex(self, vertex: V) -> List[Edge]:
    return self.edges_for_index(self.index_of(vertex))

# Make it easy to pretty-print a Graph
def __str__(self) -> str:
    desc: str = ""
    for i in range(self.vertex_count):
        desc += f"{self.vertex_at(i)} -> {self.neighbors_for_index(i)}\n"
    return desc

Dijkstra's Algorithm

Dijkstra's algorithm is a well-known algorithm for finding the shortest paths between vertices in a graph. It utilizes a priority queue to explore vertices in order of their distance from the starting vertex, updating the shortest known paths as it progresses.

Listing 4.13. dijkstra.py

from __future__ import annotations
from typing import TypeVar, List, Optional, Tuple, Dict
from dataclasses import dataclass
from mst import WeightedPath, print_weighted_path
from weighted_graph import WeightedGraph
from weighted_edge import WeightedEdge
from priority_queue import PriorityQueue

V = TypeVar('V') # type of the vertices in the graph

@dataclass
class DijkstraNode:
    vertex: int
    distance: float

    def __lt__(self, other: DijkstraNode) -> bool:
        return self.distance < other.distance

    def __eq__(self, other: DijkstraNode) -> bool:
        return self.distance == other.distance

def dijkstra(wg: WeightedGraph[V], root: V) -> Tuple[List[Optional[float]],
     Dict[int, WeightedEdge]]:
    first: int = wg.index_of(root) # find starting index
    # distances are unknown at first
    distances: List[Optional[float]] = [None] * wg.vertex_count
    distances[first] = 0 # the root is 0 away from the root
    path_dict: Dict[int, WeightedEdge] = {} # how we got to each vertex
    pq: PriorityQueue[DijkstraNode] = PriorityQueue()
    pq.push(DijkstraNode(first, 0))

    while not pq.empty:
        u: int = pq.pop().vertex # explore the next closest vertex
        dist_u: float = distances[u] # should already have seen it
        # look at every edge/vertex from the vertex in question
        for we in wg.edges_for_index(u): 
            # the old distance to this vertex
            dist_v: float = distances[we.v] 
            # no old distance or found shorter path
            if dist_v is None or dist_v > we.weight + dist_u: 
                # update distance to this vertex
                distances[we.v] = we.weight + dist_u 
                # update the edge on the shortest path to this vertex
                path_dict[we.v] = we 
                # explore it soon
                pq.push(DijkstraNode(we.v, we.weight + dist_u)) 

    return distances, path_dict

The algorithm begins by initializing distances to all vertices as unknown (None), except for the starting vertex, which is set to zero. It then explores each vertex, updating the shortest known paths and distances as it progresses through the graph.